And*_*lis 17 bash shell grep cut tail
我正在尝试构建一个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 " "
Run Code Online (Sandbox Code Playgroud)
日志文件如下:
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
Run Code Online (Sandbox Code Playgroud)
我的问题是命令的输出不显示最后一行
some test and p l a c e h o l d e r 6
Run Code Online (Sandbox Code Playgroud)
直到排队
some test and p l a c e h o l d e r 7
Run Code Online (Sandbox Code Playgroud)
被添加到日志中.
我希望我明白我的问题.任何人都可以帮我解决这个问题吗?谢谢 :)
nul*_*ion 22
问题几乎肯定与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
Run Code Online (Sandbox Code Playgroud)
(别忘了; 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}'
Run Code Online (Sandbox Code Playgroud)
请访问http://www.pixelbeat.org/programming/stdio_buffering/了解有关缓冲问题的更多信息.