简体   繁体   English

Bash-在每个grep对应关系上运行命令,而不停止tail -n0 -f

[英]Bash- Running a command on each grep correspondence without stopping tail -n0 -f

I'm currently monitoring a log file and my ultimate goal is to write a script that uses tail -n0 -f and execute a certain command once grep finds a correspondence. 我目前正在监视日志文件,我的最终目标是编写一个使用tail -n0 -f的脚本,并在grep找到对应关系后执行某个命令。 My current code: 我当前的代码:

tail -n 0 -f $logfile | grep -q $pattern && echo $warning > $anotherlogfile

This works but only once, since grep -q stops when it finds a match. 这只能工作一次,因为grep -q在找到匹配项时会停止。 The script must keep searching and running the command, so I can update a status log and run another script to automatically fix the problem. 该脚本必须继续搜索并运行命令,因此我可以更新状态日志并运行另一个脚本以自动解决问题。 Can you give me a hint? 你能给我一个提示吗?

Thanks 谢谢

use a while loop 使用while循环

tail -n 0 -f "$logfile" | while read LINE; do
    echo "$LINE" | grep -q "$pattern" && echo "$warning" > "$anotherlogfile"
done

awk will let us continue to process lines and take actions when a pattern is found. awk将让我们继续处理线并在找到模式后采取行动。 Something like: 就像是:

tail -n0 -f "$logfile" | awk -v pattern="$pattern" '$0 ~ pattern {print "WARN" >> "anotherLogFile"}'

If you need to pass in the warning message and path to anotherLogFile you can use more -v flags to awk . 如果您需要将警告消息和路径传递到anotherLogFile ,则可以将更多-v标志用于awk Also, you could have awk take the action you want instead. 同样,您可能会awk采取所需的操作。 It can run commands via the system() function where you pass the shell command to run 它可以通过system()函数运行命令,在此您传递shell命令以运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM