bash 通过 grep 两次管道尾部输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13858912/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:01:17  来源:igfitidea点击:

Piping tail output though grep twice

bashshellunixgreptail

提问by Craig Francis

Going with a typical Apache access log, you can run:

使用典型的 Apache 访问日志,您可以运行:

tail -f access_log | grep "127.0.0.1"

Which will only show you the logs (as they are created) for the specified IP address.

它只会向您显示指定 IP 地址的日志(创建时)。

But why does this fail when you pipe it though grepa second time, to further limit the results?

但是为什么当你grep第二次通过管道传输时会失败,以进一步限制结果?

For example, a simple exclude for ".css":

例如,“.css”的简单排除:

tail -f access_log | grep "127.0.0.1" | grep -v ".css"

won't show any output.

不会显示任何输出。

回答by Shawn Chin

I believe the problem here is that the first grep is buffering the output which means the second grep won't see it until the buffer is flushed.

我相信这里的问题是第一个 grep 正在缓冲输出,这意味着在刷新缓冲区之前第二个 grep 不会看到它。

Try adding the --line-bufferedoption on your first grep:

尝试--line-buffered在您的第一个 grep 上添加选项:

tail -f access_log | grep --line-buffered "127.0.0.1" | grep -v ".css"

For more info, see "BashFAQ/009 -- What is buffering? Or, why does my command line produce no output: tail -f logfile | grep 'foo bar' | awk ..."

有关更多信息,请参阅“BashFAQ/009 -- 什么是缓冲?或者,为什么我的命令行没有输出:tail -f logfile | grep 'foo bar' | awk ...

回答by Thor

This is the result of buffering, it will eventually print when enough data is available.

这是缓冲的结果,当有足够的数据可用时,它最终会打印。

Use the --line-bufferedoption as suggested by Shawn Chinor if stdbufis available you can get the same effect with:

使用Shawn Chin--line-buffered建议的选项,或者如果可用,您可以获得相同的效果:stdbuf

tail -f access_log | stdbuf -oL grep "127.0.0.1" | grep -v ".css"