【问题标题】:tail -f into grep into cut not working properlytail -f into grep into cut 不能正常工作
【发布时间】:2012-12-30 21:41:12
【问题描述】:

我正在尝试构建一个 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

被添加到日志中。

我希望我能明确我的问题。谁能帮我解决这个问题? 谢谢你:)

【问题讨论】:

  • 也许日志行没有以换行符结束,而是以一个换行符开始?在这种情况下,直到第 7 行开始并提供该换行符,第 6 行才真正完成。如果您查看显示所有字符的日志文件,您是否在最后一行的末尾看到换行符?
  • 使用od -c /var/somelog查找尾随换行符(“\n”)。
  • 您是否看到与 tail -f 相同的输出?如果是这种情况,那么@David 已经正确指出了这一点。
  • 我现在不在工作,但如果我运行 tail -f 我可以看到完整的日志。今晚我将尝试您的解决方案并及时通知您:)
  • 我猜你会看到tail -f的完整输出(包括最后一行),甚至tail -f | grep --line-buffered "pattern",但是一旦你将cut引入管道,你就会丢失最后一行.

标签: bash shell grep tail cut


【解决方案1】:

这个问题几乎肯定与 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/ 了解有关缓冲问题的更多信息。

【讨论】:

  • 很可能写入/var/somelog 的任何内容都在缓冲,因此tail 甚至可能看不到更改,直到它溢出缓冲区或以其他方式刷新其输出...
  • 我已经尝试了第一个解决方案并且正在工作。感谢您的帮助!
  • 很高兴为您提供帮助。不要忘记,在这里表示感谢的最佳方式是接受/支持有用的答案! :)
  • 天哪,我不敢相信,但 cut 似乎缓冲了它的输出,而 grep 等人却没有。哦,感觉很蹩脚的人......
猜你喜欢
  • 1970-01-01
  • 2016-04-18
  • 2014-03-17
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
相关资源
最近更新 更多