管道 tail -f 切割到 sed 不产生任何输出

Piping tail -f to cut to sed produces no output

我尝试使用以下命令在终端中显示命名管道:

tail -f textFile | cut -d " " -f 3- | sed -e "s/a/g&g/"

出于某种原因,这不会产生任何输出。

如果删除 -f,它确实会按预期工作:

tail textFile | cut -d " " -f 3- | sed -e "s/a/g&g/"

或者删除cut语句:

tail -f textFile | sed -e "s/a/g&g/"

或删除sed语句:

tail -f textFile | cut -d " " -f 3-

只有当这三个东西都在的时候,突然就没有输出了。 sed 和 cut 的顺序没有区别。所有这些让我很难责怪任何一个或一对这些程序的输入或输出缓冲行为。

获得所需功能的可能解决方案是 while read line 结构,但我想尽可能避免为每一行初始化命令。

我遇到了与要过滤的 ping 命令类似的问题。

以下网页似乎解释了问题所在(stdio 缓冲) http://www.pixelbeat.org/programming/stdio_buffering/

该网站指出了一个解决方案,该解决方案涉及使用 "stdbuf" 命令

禁用缓冲
tail -f filename | stdbuf -o0 cut -d " " -f 3- | sed -e "s/a/g&g/"

以上对我来说效果很好,删除 "stdbuf -o0" 会导致不显示任何输出。

>stdbuf --help
Usage: stdbuf OPTION... COMMAND
Run COMMAND, with modified buffering operations for its standard streams.

Mandatory arguments to long options are mandatory for short options too.
  -i, --input=MODE   adjust standard input stream buffering
  -o, --output=MODE  adjust standard output stream buffering
  -e, --error=MODE   adjust standard error stream buffering
      --help     display this help and exit
      --version  output version information and exit