[英]How to do something with Bash when a text line appears in a file
我想在日志文件中出現某個文本時立即運行命令。 我怎么用Bash做到這一點?
使用命令
tail -f file.log | grep --line-buffered "my pattern" | while read line
do
echo $line
done
--line-buffered
是關鍵,否則讀取將失敗。
僅使用tail
:
tail -f file.log | while read line; do if [[ $line == *text* ]]; then
mycommand
fi; done
即使沒有GNU grep,這應該可以工作:
tail -f -n 0 logfile.out | nawk '/pattern/ {system("echo do something here")}'
編輯:添加“-n 0”,以便只匹配文本的新出現。
您也可以查看inotail
,它是tail -f
的替代品,它使用inotify
框架僅在您感興趣的文件發生更改時才喚醒。 通常的tail -f
只是在輪詢之間短時間內睡覺,這是一種有效但不是非常有效的解決方案。
我喜歡matli的回答。 Bruno De Fraine的答案也很好,它只使用shell命令,而不是其他程序(如awk)。 它遇到的問題是整行必須匹配魔術字符串。 從問題中不清楚這是要求的一部分。
我會稍微修改它來處理原始問題中的“盡快”條款
logfile_generator | tee logfile.out | nawk '/pattern/ {system("echo do something here")}'
其中logfile_generator是首先生成日志文件的程序。 一旦魔術弦被定位,該修改就執行“某事”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.