【问题标题】:Piping ping through awk and redirecting output to a file通过 awk 管道 ping 并将输出重定向到文件
【发布时间】:2021-01-06 23:54:34
【问题描述】:

我的想法是不断 ping 地址,提取一些信息,然后将其写入文件。

这是我尝试过的:

$ ping google.com | awk -F' ' '{ time = split($8, arr, "time="); print arr[2] }' > file.log

然后等待几秒钟,然后执行:

$ file file.log
file.log: empty

但是,这可以按预期工作(为 ping 输出中的每一行打印 time=):

$ ping google.com | awk -F' ' '{ time = split($8, arr, "time="); print arr[2] }'

这也有效:

$ echo "64 bytes from some.net (x.x.x.x): icmp_seq=7 ttl=115 time=16.7 ms" | awk -F' ' '{ time = split($8, arr, "time="); print arr[2] }' > file.log
$ cat file.log
16.7

这很有效:

$ ping -c 1 google.com | awk -F' ' '{ time = split($8, arr, "time="); print arr[2] }' > file.log

只有当我继续 ping 时它才不起作用。我的file.log 仍然是空的。

如何实现 ping 不断运行并填充我的 file.log

【问题讨论】:

    标签: linux shell awk


    【解决方案1】:

    到标准输出的输出通常是缓冲的——在缓冲区满之前什么都不写。到 stderr 的输出通常会立即写入。

    你可以试试:

    ping google.com |\
    awk 'sub("time=","",$8) { print $8 >"/dev/stderr" }' 2>file.log
    

    或:

    ping google.com |\
    awk ' sub("time=","",$8) { print $8; fflush() }' >file.log
    

    【讨论】:

    • 啊...再次缓冲。 flush() 完成这项工作。
    猜你喜欢
    • 2021-10-15
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多