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
另外我希望它连续运行,它不应该等待命令终止后再打印结果。
答案1
从 :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
答案2
-D
正如大多数答案所暗示的那样,我认为修改 给出的 UNIX 时间戳太复杂了。为什么不直接创建自己的时间戳并将其粘贴到每行的前面:
ping localhost | while read l; do echo `date` $l; done
date
您可以根据需要为 提供任何格式选项。
答案3
ping google.com | awk '/^[0-9]+ bytes from / { "date" | getline pong; close("date"); print pong":",$0; }'
这来自http://tech.jocke.no/2010/09/27/add-timestamp-to-ping/
效果也很好!
答案4
这在 macOS 上对我有用:
ping -i 5 google.com | while read pong; do echo "$(date -j '+%Y-%m-%d %H:%M:%S') $pong"; done
改编自此处给出的命令:http://shawnreeves.net/wiki/index.php?title=Ping_with_timestamp_on_Mac_OS_X
输出如下所示:
2021-10-10 13:23:21 PING google.com (142.250.80.14): 56 data bytes
2021-10-10 13:23:21 64 bytes from 142.250.80.14: icmp_seq=0 ttl=115 time=83.045 ms
2021-10-10 13:23:26 64 bytes from 142.250.80.14: icmp_seq=1 ttl=115 time=39.765 ms