Scripting

如何讓 ping 列印人類可讀的時間戳?

  • October 10, 2021

Ping 可以在每一行列印一個時間戳,但它是 unix 日期格式:(

ping -D localhost  
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
[1415629479.482938] 64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=1 ttl=64 time=0.057 ms

我正在尋找一個簡單的管道命令,可以將它們即時轉換成這樣的東西:

[Sat 14 Feb 2009 01:31:30 SAST] 64 bytes from localhost.localdomain (127.0.0.1): icmp_seq=1 ttl=64 time=0.057 ms

另外我希望它連續執行,它不應該在列印結果之前等待命令終止。

來自:https ://stackoverflow.com/questions/14036116/convert-timestamp-to-datetime-with-sed

用一點腳本……

ping -D localhost | while read row 
do 
 awk '{ sub(/[0-9]{10}/, strftime("%Y-%m-%d %H:%M:%S", substr($0,2,10))) }1' <<< "$row"
done

執行為

$ ping -D localhost | while read row; do awk '{ sub(/[0-9]{10}/, strftime("%Y-%m-%d %H:%M:%S", substr($0,2,10))) }1' <<< "$row" ; done
PING localhost (127.0.0.1) 56(84) bytes of data.
[2014-11-10 16:06:40.145811] 64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.045 ms
[2014-11-10 16:06:41.144926] 64 bytes from localhost (127.0.0.1): icmp_req=2 ttl=64 time=0.040 ms

引用自:https://unix.stackexchange.com/questions/167778