简体   繁体   English

当文本行出现在文件中时,如何使用Bash执行某些操作

[英]How to do something with Bash when a text line appears in a file

I want to run a command as soon as a certain text appears in a log file. 我想在日志文件中出现某个文本时立即运行命令。 How do I do that in Bash? 我怎么用Bash做到这一点?

Use command 使用命令

tail -f file.log | grep --line-buffered "my pattern" | while read line
do
  echo $line
done

The --line-buffered is the key here, otherwise the read will fail. --line-buffered是关键,否则读取将失败。

Using only tail : 仅使用tail

tail -f file.log | while read line; do if [[ $line == *text* ]]; then
    mycommand
fi; done

This should work even without GNU grep: 即使没有GNU grep,这应该可以工作:

tail -f -n 0 logfile.out | nawk '/pattern/ {system("echo do something here")}'

edit: Added "-n 0" so that only new occurences of the text will be matched. 编辑:添加“-n 0”,以便只匹配文本的新出现。

Also you might look at inotail , a replacement for tail -f which uses the inotify framework to wake up only when the file you're interested in has changed. 您也可以查看inotail ,它是tail -f的替代品,它使用inotify框架仅在您感兴趣的文件发生更改时才唤醒。 The usual tail -f just sleeps for short periods of time between polling, which is an effective but not very efficient solution. 通常的tail -f只是在轮询之间短时间内睡觉,这是一种有效但不是非常有效的解决方案。

I like matli's answer. 我喜欢matli的回答。 Bruno De Fraine's answer is also good in that it uses only shell ccommands, not other programs (like awk). Bruno De Fraine的答案也很好,它只使用shell命令,而不是其他程序(如awk)。 It suffers from the problem that the entire line must match the magic string. 它遇到的问题是整行必须匹配魔术字符串。 It's not clear from the question that's part of the requirment. 从问题中不清楚这是要求的一部分。

I would modify it a tiny bit to deal with the "as soon as" clause in the original question 我会稍微修改它来处理原始问题中的“尽快”条款

logfile_generator | tee logfile.out | nawk '/pattern/ {system("echo do something here")}'

where logfile_generator is the program that is generating the log file in the first place. 其中logfile_generator是首先生成日志文件的程序。 This modification executes the "something" as soon as the magic string is located. 一旦魔术弦被定位,该修改就执行“某事”。

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

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