grep的管道不适用于尾巴?

时间:2014-10-14 13:46:03

标签: regex linux bash grep

我试图通过检查日志调试一个场景,这是我的命令

tail -f eclipse.log | grep 'enimation' | grep  -i 'tap'

基本上我想要的是,在所有的线条中,我在其中打印带有enimation的线条,然后是所有动画,我希望用" tap"在它。

以下是返回空结果的sammple数据

*******enimation error*********TapExpand
*******enimation error*********TapShrink

这将返回空结果。

如果我运行此命令

 tail -f eclipse.log | grep  -i 'enimation.*tap'

它会返回正确的结果。有人可以向我解释一下,上述两个命令之间的区别是什么以及为什么结果存在差异。它们看起来都和我一模一样。

4 个答案:

答案 0 :(得分:5)

grep正在缓冲它的输出。要告诉GNU grep吐出输出逐行,您需要在--line-buffered中使用grep选项才能使其正常工作:

tail -f eclipse.log | grep --line-buffered 'enimation' | grep --line-buffered -i 'tap'

根据man grep

--line-buffered
    Force output to be line buffered.  By default, output is line buffered when standard
    output is a terminal and block buffered otherwise.

答案 1 :(得分:3)

中间grep的输出不是终端,因此它使用块缓冲而不是行缓冲。您必须使用--line-buffered选项强制进行行缓冲。

tail -f eclipse.log | grep --line-buffered 'enimation' | grep  -i 'tap'

如果其他命令没有提供这样的选项,您可以使用stdbuf命令强制进行行缓冲,例如:

tail -f eclipse.log | stdbuf -o1 grep 'enimation' | grep  -i 'tap'

答案 2 :(得分:1)

您的输出正在缓冲。尝试:

tail -f eclipse.log | grep --line-buffered 'enimation' | grep --line-buffered -i 'tap'

答案 3 :(得分:-2)

尝试将-E选项添加到grep。没有它,许多反射功能都无法工作。我通常将其称为“是的,我知道我在做什么”选项。