bash tail -f into grep into cut 无法正常工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14360640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
tail -f into grep into cut not working properly
提问by Andrea Tullis
i'm trying to build a shell script to monitor some log files. I'm using a command like this:
我正在尝试构建一个 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 " "
the log file is like:
日志文件是这样的:
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
and so on.. My issue is that the output of the command does not display the last line
等等..我的问题是命令的输出不显示最后一行
some test and p l a c e h o l d e r 6
until line
直到线
some test and p l a c e h o l d e r 7
is added to the log.
被添加到日志中。
I hope I made clear my issue. Can anyone help me to solve this? Thank you :)
我希望我说清楚了我的问题。谁能帮我解决这个问题?谢谢 :)
回答by nullrevolution
the problem is almost certainly related to how grep and cut buffer their output. here's a hack that should get you around the problem, though i'm sure there are prettier ways to do it:
问题几乎肯定与 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
(don't forget the ; doneat the end of the command)
(不要忘记; done命令末尾的 )
alternatively, because gawkdoesn't buffer it's output, you could use it in place of cutto avoid the cumbersome while loop:
或者,因为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 ,,}'
check out http://www.pixelbeat.org/programming/stdio_buffering/for more info on buffering problems.
查看http://www.pixelbeat.org/programming/stdio_buffering/了解更多关于缓冲问题的信息。

