Pipe Output – Why Does Grep Change the Length of Output Lines?

dpkgoutputpipe

I often use dpkg or aptitude combined with grep when I want to list certain packages available or installed on my system, but I noticed that when I add | grep, the output lines look a little bit different.

Here's a pure dpkg output, the first command was typed when the terminal was smaller, the second one when the terminal was maximized:

screen

As you can see, the output differs depending on the size of the window — the spaces are reduced in the case of a smaller one.

Now, what happens when we add | grep:

screen

A part of the first output was dropped to the second line. But when I maximised the terminal and typed the command once more, the line is in one piece. Moreover, the columns have the same fixed size (the same spaces between them).

This is an aptitude output:

screen

Both commands were typed in the maximised window, but the grep line has narrower columns, and some text of the third column was cut off.

Why does it happen? Is there a way to stop grep from resizing the lines?

I don't know how to add an image without changing its parameters, I hope you see what I'm talking about.

Best Answer

It is not grep changing the output. It is dpkg and aptitude. They check whether the output goes to a terminal or to some other command.

If it is a terminal they adapt their own output width to match the terminal size.

If the output does not go to a terminal, the command has no idea what column size would be appropriate. (The output might as well end in some file.)

The same happens with ls. Compare ls and ls|cat.


There is no general way to solve this, but some commands might have specific options for that. For example aptitude has --disable-columns and -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).

The man page of dpkg says:

   COLUMNS
          Sets the number of columns dpkg should use when
          displaying formatted text. Currently only used by -l.
Related Question