立即在管道中处理来自“ping”的每一行输出

Gre*_*bet 4 pipe

我有几个从ping -c 10 google.com. 对于其中一些管道,每隔一段时间就会产生一行输出,就像 ping 的输出一样。对于其他人,在处理完所有输出行后,会立即发出所有输出行。我什么时候会看到第一种行为,什么时候会看到第二种行为,有什么好的规则吗?

# prints output for each line as soon as it is received
# on OS X and Linux.
ping -c 10 google.com | grep -o 'time=\S*'

# prints output for each line as soon as it is received on OS X
# but not on Linux 
# (the output of ping is slightly different so it's $8 on Linux to get the time)
ping -c 10 google.com | awk '{ print $7 }'

# waits until all input is received on OS X and Linux
ping -c 10 google.com | awk -F ':' '{ print $2 }'

# prints output for line as soon as it is received on Linux and OS X
ping -c 10 google.com | sed -e 's/^.*time=\(.*\) .*$/\1/'

# waits for the end of input on OS X and Linux
ping -c 10 google.com | grep -o 'time\S*' | sed -e 's/time=//'

# as a quick check, this prints each line of output immediately 
# on OS X and Linux
ping -c 10 google.com | sed -e 's/time=//' 
Run Code Online (Sandbox Code Playgroud)

环顾四周后,这似乎只是行缓冲的问题,一些标准实用程序在交互使用和非交互使用时表现不同。

小智 8

这与这些程序如何处理缓冲有关。

如果您希望 grep 立即输出管道数据,请将其与选项 --line-buffered 一起使用。

ping -c 10 google.com | grep --line-buffered -o 'time\S*' | sed -e 's/time=//'
Run Code Online (Sandbox Code Playgroud)

如果您希望 awk 立即输出管道数据,您可以使用选项 -W 交互。

ping -c 10 google.com | awk -W interactive '{ print $7 }'
Run Code Online (Sandbox Code Playgroud)

您应该阅读这些应用程序的手册页以了解更多信息。