32

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

tail -f access_log | grep "127.0.0.1"

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

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

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

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

不会显示任何输出。

4

2 回答 2

53

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

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

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

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

于 2012-12-13T11:37:42.430 回答
13

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

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

tail -f access_log | stdbuf -oL grep "127.0.0.1" | grep -v ".css"
于 2012-12-13T11:40:06.927 回答