当我想列出系统上可用或安装的某些软件包时,我经常使用dpkg或aptitude结合使用grep,但我注意到当我添加时| grep,输出行看起来有点不同。
这是一个纯dpkg输出,当终端较小时输入第一个命令,当终端最大化时输入第二个命令:

如您所见,输出因窗口大小而异——在窗口较小的情况下,空间会减少。
现在,当我们添加时会发生什么| grep:

第一个输出的一部分被放到了第二行。但是当我最大化终端并再次输入命令时,该行是一条直线。此外,列具有相同的固定大小(它们之间的间距相同)。
这是一个aptitude输出:
这两个命令都是在最大化的窗口中输入的,但该grep行的列更窄,并且第三列的一些文本被截断了。
为什么会发生?有没有办法阻止grep调整线条的大小?
我不知道如何在不更改其参数的情况下添加图像,希望您明白我在说什么。
它不会grep改变输出。它是dpkg和aptitude。他们检查输出是否进入终端或其他一些命令。
如果是终端,它们会调整自己的输出宽度以匹配终端大小。
如果输出没有到达终端,则该命令不知道合适的列大小。(输出也可能以某个文件结尾。)
同样的情况发生在ls. 比较ls和ls|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)