做一个 tail -F 直到匹配一个模式 [英] Do a tail -F until matching a pattern
问题描述
我想对文件执行 tail -F
直到匹配模式.我找到了一种使用 awk
的方法,但恕我直言,我的命令并不是很干净.问题是由于某些限制,我需要只在一行中完成.
I want to do a tail -F
on a file until matching a pattern. I found a way using awk
, but IMHO my command is not really clean. The problem is that I need to do it in only one line, because of some limitations.
tail -n +0 -F /tmp/foo |
awk -W interactive '{if ($1 == "EOF") exit; print} END {system("echo EOF >> /tmp/foo")}'
尾部将阻塞,直到 EOF
出现在文件中.它工作得很好.END 块是强制性的,因为 awk 的 exit
不会立即退出.在退出之前,它使 awk
成为 eval
END 块.END 块挂在读取调用上(因为 tail),所以我需要做的最后一件事是在文件中写入另一行以强制 tail 退出.
The tail will block until EOF
appears in the file. It works pretty well. The END block is mandatory because awk's exit
does not exit right away. It makes awk
to eval
the END block before quitting. The END block hangs on a read call (because of tail), so the last thing I need to do, is to write another line in the file to force tail to exit.
有人知道更好的方法吗?
Does someone know a better way to do that?
推荐答案
试试这个:
sh -c 'tail -n +0 -f /tmp/foo | { sed "/EOF/ q" && kill $$ ;}'
只要EOF"出现,整个命令行就会退出.字符串可见于 /tmp/foo
.
The whole command-line will exit as soon as the "EOF" string is seen in /tmp/foo
.
有一个副作用:tail
进程将一直运行(在后台),直到将任何内容写入 /tmp/foo
.
There is one side-effect: the tail
process will be left running (in the background) until anything is written to /tmp/foo
.
这篇关于做一个 tail -F 直到匹配一个模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!