19

我正在尝试构建一个 shell 脚本来监视一些日志文件。我正在使用这样的命令:

tail -f /var/somelog | grep --line-buffered " some test and p l a c e h o l d e r" | cut -f 3,4,14 -d " "

日志文件如下:

some test and p l a c e h o l d e r 3
some test and p l a c e h o l d e r 4
some test and p l a c e h o l d e r 5
some test and p l a c e h o l d e r 6

等等..我的问题是命令的输出不显示最后一行

some test and p l a c e h o l d e r 6

直到线

some test and p l a c e h o l d e r 7

被添加到日志中。

我希望我能说清楚我的问题。谁能帮我解决这个问题?谢谢 :)

4

1 回答 1

25

这个问题几乎肯定与 grep 和 cut 如何缓冲它们的输出有关。这是一个可以解决问题的技巧,尽管我确信有更漂亮的方法可以做到:

tail -f /var/somelog | while read line; do echo "$line" | grep "some test and p l a c e h o l d e r" | cut -f 3,4,14 -d " "; done

(不要忘记; done命令末尾的)

或者,因为gawk不缓冲它的输出,您可以使用它来代替,cut以避免繁琐的 while 循环:

tail -f log | grep --line-buffered "some test and p l a c e h o l d e r" | gawk '{print $3,$4,$14}'

查看http://www.pixelbeat.org/programming/stdio_buffering/了解有关缓冲问题的更多信息。

于 2013-01-16T15:40:31.910 回答