【问题标题】:Why no output is shown when using grep twice?为什么两次使用 grep 时没有显示输出?
【发布时间】:2011-07-22 14:22:51
【问题描述】:

基本上我想知道为什么这不输出任何东西:

tail --follow=name file.txt | grep something | grep something_else 

你可以假设它应该产生输出我已经运行了另一行来确认

cat file.txt | grep something | grep something_else

似乎您不能多次通过管道输出 tail !?有谁知道这笔交易是什么,有解决办法吗?

编辑: 要回答到目前为止的问题,该文件肯定包含 grep 应该显示的内容。如果 grep 是这样完成的,作为证据:

tail --follow=name file.txt | grep something

输出正确显示,但如果使用它来代替:

tail --follow=name file.txt | grep something | grep something

没有显示输出。

如果有帮助,我正在运行 ubuntu 10.04

【问题讨论】:

标签: linux file command-line grep pipe


【解决方案1】:

grep 模式文件名 | grep 模式 | grep 模式 | grep 模式......

【讨论】:

  • 当然可以,但是与tail的组合是这个问题的重要部分......
【解决方案2】:

在管道内时,您可能还会遇到 grep 缓冲问题。 即,您看不到来自

的输出
   tail --follow=name file.txt | grep something > output.txt

因为 grep 会缓冲它自己的输出。

使用 grep 的 --line-buffered 开关来解决这个问题:

tail --follow=name file.txt | grep --line-buffered something > output.txt

如果您想尽快将后续结果放入 output.txt 文件中,这很有用。

【讨论】:

  • 刚刚检查了这个并检查了您的解决方案。比我的解决方法更干净、更精确,标记为正确的解决方案。
【解决方案3】:

弄清楚这里发生了什么。事实证明,该命令正在运行,只是输出需要很长时间才能到达控制台(在我的情况下大约需要 120 秒)。这是因为标准输出上的缓冲区不是写入每一行而是写入每个块。因此,我不会在写入文件时从文件中获取每一行,而是每 2 分钟左右得到一个巨大的块。

需要注意的是,这可以正常工作:

tail file.txt | grep something | grep something

有问题的是带有--follow=name 的文件的以下内容。

出于我的目的,我找到了一种解决方法,我打算将第一个 grep 的输出捕获到文件中,所以命令是:

tail --follow=name file.txt | grep something > output.txt

解决这个问题的一种方法是像这样使用script 命令:

script -c 'tail --follow=name file.txt | grep something' output.txt

脚本捕获命令的输出并将其写入文件,从而避开第二个管道。

这对我来说有效地解决了这个问题,我已经解释了为什么该命令没有按预期工作,问题已解决。

仅供参考,这些其他 stackoverflow 问题是相关的:
Trick an application into thinking its stdin is interactive, not a pipe
Force another program's standard output to be unbuffered using Python

【讨论】:

    【解决方案4】:

    在没有 --follow=name 的情况下在 Mac 上为我工作

    bash-3.2$ tail delme.txt | grep po
    position.bin
    position.lrn
    bash-3.2$ tail delme.txt | grep po | grep lr
    position.lrn
    

    【讨论】:

    • 试过了,它实际上也对我有用,但是 --follow=name 部分对我想要实现的目标至关重要
    • 当然没有follow部分也可以工作,因为这是由缓冲引起的,一旦grep(没有follow)退出,缓冲就会被刷新。
    【解决方案5】:

    你知道tail 默认从文件的最后十行开始吗?我的猜测是cat 版本发现的一切都已成为过去。尝试tail -n+1 --follow=name file.txt 从文件开头开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 2020-11-13
      • 2022-11-21
      • 2020-05-21
      相关资源
      最近更新 更多