如何在 TAILING 文件时使用每个 GREP 结果执行命令
How to execute a command with each GREP result while TAILING a file
TL;DR:如何对通过管道将 tail -f 传输到 grep 时产生的每个 grep 匹配项执行命令。
我目前正在使用 tail -f file | grep exception
来跟踪服务抛出的所有异常。问题之一是出现异常的行没有我需要的所有信息,但它包含一个 ID
标识该请求生成的所有日志行。
我想做的是打印所有具有特定ID
的行,一旦grep匹配异常的行。
使用这个问题的帮助
How to grep and execute a command (for every 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,您的手册页可能指出 "Direct invocation as either egrep or fgrep is deprecated, but is provided to allow historical applications that rely on them to run unmodified." 虽然老实说,我从未见过 egrep消失,其他平台(FreeBSD,OSX)没有提到弃用。
TL;DR:如何对通过管道将 tail -f 传输到 grep 时产生的每个 grep 匹配项执行命令。
我目前正在使用 tail -f file | grep exception
来跟踪服务抛出的所有异常。问题之一是出现异常的行没有我需要的所有信息,但它包含一个 ID
标识该请求生成的所有日志行。
我想做的是打印所有具有特定ID
的行,一旦grep匹配异常的行。
使用这个问题的帮助 How to grep and execute a command (for every 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,您的手册页可能指出 "Direct invocation as either egrep or fgrep is deprecated, but is provided to allow historical applications that rely on them to run unmodified." 虽然老实说,我从未见过 egrep消失,其他平台(FreeBSD,OSX)没有提到弃用。