[英]How to execute a command with each GREP result while TAILING a file
TL;DR:如何在将 tail -f 管道传输到 grep 时产生的每个 grep 匹配项上执行命令。
我目前正在使用tail -f file | grep exception
tail -f file | grep exception
跟踪服务抛出的所有异常。 问题之一是具有异常的行没有我需要的所有信息,但它确实包含标识该请求生成的所有日志行的ID
。
我想要做的是在 grep 与异常行匹配时打印所有具有特定ID
的行。
使用此问题的帮助How to grep and execute a command (for each match)
我设法使它适用于CAT
命令,如下所示:
cat myFile |
egrep -i "exception" | #find lines with exception
egrep -o "ID=[A-Z]{10}" | #for those lines, select out only the id
while read line; do #for each id
cat myFile | grep $line; #show all the lines that have that id
done
工作正常并打印具有匹配 ID 的所有行,但是当我将cat
更改为tail -f
它不起作用,它不会打印任何内容。 我究竟做错了什么?
您遇到的问题很可能是 grep 在看到其输出是另一个管道时正在缓冲其输出。 如果您等待足够长的时间等待缓冲区填满,您的命令最终可能会产生输出。
相反,请尝试以下操作:
< myFile egrep --line-buffered -i "exception" \
| egrep --line-buffered -o "ID=[A-Z]{10}" \
| while read line; do
cat myFile | grep "$line"
done
(是的,该输入重定向选项应该可以正常工作。:])
相关的手册页摘录是:
--line-buffered
Use line buffering on output. This can cause a performance penalty.
除非您知道自己在寻找什么,否则这显然不会对您有多大帮助。 :-P
请注意,在 Linux 世界中,您使用的是 Linux,其中您的手册页可能指出“不推荐使用 egrep 或 fgrep 的直接调用,但提供它是为了允许依赖它们的历史应用程序未经修改地运行。” 老实说,我没有看到 egrep 消失,其他平台(FreeBSD、OSX)也没有提到弃用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.