使用 shell 脚本在实时日志(文本)文件中查找用户定义的关键字

Find a user defined keyword in real-time log (text) file using shell script

我是 运行 linux 中的一个进程,它以文本格式将状态和其他信息记录在日志文件 /home/path/Detail_File.log 中。该文件正在使用后台进程连续写入。我可以使用 tail -f /home/path/Detail_File.log.

显示文件内容

我想检查文件中的关键字 keyword(比方说)。如何连续检查是否找到关键字,如果找到,则将该行放入变量中。

我不确定我应该在互联网上搜索什么,所以在没有初步研究的情况下直接发布这个问题。如有任何建议,我们将不胜感激。

编辑 1: 添加 @jhnc 的 while 循环建议截图

执行echo "Time elapsed: $curr_time ..."然后静默

如果您使用的是 GNU 实用程序,grep 有一个 --line-buffered 选项:

tail -n +1 -f /home/path/Detail_File.log |\
grep --line-buffered -F keyword |\
while read matchedline; do
    dosomething "$matchedline"
done

这是一个管道:cmd1 | cmd1 | cmd3

行尾的反斜杠 (\) 允许使用换行符以提高可读性。

  • tail 输出被送入 grep.
  • grep 输出被送入 while 循环。
  • read 的输入来自 grep,而不是用户。

通常,grep 输出会被缓冲 - 只有当管道缓冲区已满时,输出才可用。 --line-buffered 选项导致在每一行之后刷新管道缓冲区。例如,考虑输出之间的差异:

while sleep 1; do date; done |\
grep --line-buffered . |\
while read line; do echo "$(date) :: $line"; done |\
head

对比(您可能需要几分钟才能看到任何内容):

while sleep 1; do date; done |\
grep . |\
while read line; do echo "$(date) :: $line"; done |\
head