tail -f into grep into cut 无法正常工作 [英] tail -f into grep into cut not working properly
问题描述
我正在尝试构建一个 shell 脚本来监控一些日志文件.我正在使用这样的命令:
i'm trying to build a shell script to monitor some log files. I'm using a command like this:
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
等等..我的问题是命令的输出没有显示最后一行
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
直到行
some test and p l a c e h o l d e r 7
被添加到日志中.
我希望我说清楚了我的问题.谁能帮我解决这个问题?谢谢:)
I hope I made clear my issue. Can anyone help me to solve this? Thank you :)
推荐答案
这个问题几乎肯定与 grep 和 cut 如何缓冲它们的输出有关.这是一个应该可以解决问题的技巧,尽管我确信有更漂亮的方法可以做到:
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:
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
)
(don't forget the ; done
at the end of the command)
或者,因为 gawk
不缓冲它的输出,你可以用它代替 cut
来避免繁琐的 while 循环:
alternatively, because gawk
doesn't buffer it's output, you could use it in place of cut
to avoid the cumbersome while loop:
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/有关缓冲问题的更多信息.
check out http://www.pixelbeat.org/programming/stdio_buffering/ for more info on buffering problems.
这篇关于tail -f into grep into cut 无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!