为什么grep会改变输出行的长度?

Mik*_*kov 5 pipe dpkg output

当我想列出系统上可用或安装的某些软件包时,我经常使用dpkgaptitude结合使用grep,但我注意到当我添加时| grep,输出行看起来有点不同。

这是一个纯dpkg输出,当终端较小时输入第一个命令,当终端最大化时输入第二个命令:

屏幕

如您所见,输出因窗口大小而异——在窗口较小的情况下,空间会减少。

现在,当我们添加时会发生什么| grep

屏幕

第一个输出的一部分被放到了第二行。但是当我最大化终端并再次输入命令时,该行是一条直线。此外,列具有相同的固定大小(它们之间的间距相同)。

这是一个aptitude输出:

屏幕

这两个命令都是在最大化的窗口中输入的,但该grep行的列更窄,并且第三列的一些文本被截断了。

为什么会发生?有没有办法阻止grep调整线条的大小?

我不知道如何在不更改其参数的情况下添加图像,希望您明白我在说什么。

mic*_*has 8

它不会grep改变输出。它是dpkgaptitude。他们检查输出是否进入终端或其他一些命令。

如果是终端,它们会调整自己的输出宽度以匹配终端大小。

如果输出没有到达终端,则该命令不知道合适的列大小。(输出也可能以某个文件结尾。)

同样的情况发生在ls. 比较lsls|cat


没有通用的方法来解决这个问题,但有些命令可能有特定的选项。例如aptitude--disable-columns-w

   --disable-columns
       This option causes aptitude search and aptitude versions to output
       their results without any special formatting. In particular:
       normally aptitude will add whitespace or truncate search results in
       an attempt to fit its results into vertical “columns”.
       With this flag, each line will be formed by replacing any format
       escapes in the format string with the corresponding text; column
       widths will be ignored.

   -w <width>, --width <width>
       Specify the display width which should be used for output from
       the search command (by default, the terminal width is used).
Run Code Online (Sandbox Code Playgroud)

的手册页dpkg说:

   COLUMNS
          Sets the number of columns dpkg should use when
          displaying formatted text. Currently only used by -l.
Run Code Online (Sandbox Code Playgroud)

  • 管道 `|` 是 shell 内部的东西,它将终端的输出更改为一个新的描述符,该描述符设置为第二个命令的输入。第一个命令本身只能检查其输出是否为终端。某些命令可能支持命令行选项来显式设置宽度,或者它们可能会检查 $COLUMNS 环境变量。但这完全取决于命令本身。 (3认同)