一个以上的管道使输出在文本流中为空白

问题描述

此问题与this无关,因为我不想将输出重定向到多个进程。相反,我想像通常那样将输出通过管道传递两次,如下所示:

$ echo "piping twice" | cut -d 'p' -f 3 | cut -d ' ' -f 1
ing

这按预期工作! 但是,对tail -f进行相同操作将失败:

$ echo "piping twice" > somefile

# The first test passes: 
$ tail -f somefile | cut -d 'p' -f 3
ing twice

# The second test shows nothing:
$ tail -f somefile | cut -d 'p' -f 3 | cut -d ' ' -f 1

我正在使用tail作为可重现的示例,但是我实际上是在尝试解析youtube-dl的进度输出,并且不止一个管道总是导致空行。
我做错什么了吗?
谢谢。

解决方法

这将起作用:

tail -f somefile | stdbuf -oL cut -d 'p' -f 3| cut -d ' ' -f 1

由于大多数Linux程序将在stdout连接到TTY时使用行缓冲,否则将使用全缓冲。您可以使用stdbuf强制行缓冲。