grep 和 tail -f?

xen*_*ide 46 command-line shell grep tail

是否可以同时对文件执行tail -f(或类似操作)grep?我不介意其他命令只是寻找那种行为。

Ste*_*n D 65

使用 GNUtail和 GNU grep,我可以tail -f使用简单的语法grep a :

tail -f /var/log/file.log | grep search_term
Run Code Online (Sandbox Code Playgroud)


小智 13

添加--line-bufferedgrep,这可能会减少您的延迟。在某些情况下非常有用。

tail -f foo | grep --line-buffered bar
Run Code Online (Sandbox Code Playgroud)

  • 当 `grep` 的输出没有进入终端(重定向到另一种类型的文件)时,这很有用。行缓冲是输出到终端时的默认设置,因此在那里不会有任何区别。请注意,该选项是特定于 GNU 的。 (2认同)

小智 9

我看到所有这些人都说要使用tail -f,但我不喜欢它的限制!我最喜欢的搜索文件同时监视新行的方法(例如,我通常使用日志文件,其中附加了通过 cron 作业定期执行的进程的重定向输出)是:

 tail -Fn+0 /path/to/file|grep searchterm
Run Code Online (Sandbox Code Playgroud)

这假设使用 GNU tail 和 grep。尾部联机帮助页中的支持详细信息(GNU coreutils,我的是 v8.22)[ https://www.gnu.org/software/coreutils/manual/coreutils.html]

 -F     same as --follow=name --retry
 -n, --lines=K
         output the last K lines, instead of the last 10; or use -n +K to output
         starting with the Kth.
         If  the first character of K (the number of bytes or lines)
         is a '+', print beginning with the Kth item from the start
         of each file, otherwise, print the last K items in the file.
         K may have a multiplier suffix: b 512, kB 1000, K 1024, MB
         1000*1000, M 1024*1024, GB 1000*1000*1000, G 1024*1024*1024,
         and so on for T, P, E, Z, Y.

  With --follow (-f), tail defaults to following the file descriptor,
  which means that even if a tail'ed file is renamed, tail will
  continue to track its end.  This default behavior is  not  desirable
  when  you  really  want  to  track the actual name of the file, not
  the file descriptor (e.g., log rotation).  Use --follow=name in
  that case.  That causes tail to track the named file in a way that
  accommodates renaming, removal and creation.
Run Code Online (Sandbox Code Playgroud)

因此,我的命令的尾部部分等于tail --follow --retry --lines=+0,其中最后一个参数指示它从开头开始,跳过零行。


Mic*_*zek 7

它会正常工作;更一般地,grep当程序没有输出时会等待,并在输出进入时继续阅读,所以如果你这样做:

$ (echo foo; sleep 5; echo test; sleep 5) | grep test
Run Code Online (Sandbox Code Playgroud)

5 秒内什么都不会发生,然后 grep 将输出匹配的“测试”,然后在 5 秒后它会在管道进程执行时退出


Gil*_*il' 5

您可以将 的输出通过管道传输tail -fgrep。还有一些程序将tail -f功能与过滤和着色相结合,特别是多尾示例)。