18

When I do

ps aux

The output gets nicely trimmed to the width of my terminal, so that long process descriptions don't take more than one line. However, if I pipe it into anything else, the long lines return.

I realize this is a proper behavior, since ps is no longer outputting to a tty and the entire output might be crucial for processing. What I want is another util that will crop the output back when I'm done.

I want to be able to do something like this:

ps aux | grep -v 'www-data' | nowrap  

nowrap is the imaginary tool which I'm looking for. It will make sure long lines get cropped and not overflow.

Is there something like this?

3 Answers 3

23

You can use the cut command to slice the output. For example:

ps aux | grep -v 'www-data' | cut -c-80

This will keep only the first 80 characters of each line. You can of course set that to any width you want.

If using the bash commandline, you could do this:

ps aux | grep -v 'www-data' | cut -c-$COLUMNS

If the output has tabs, then the width may not be computed correctly. expand can turn tabs into spaces:

ps aux | grep -v 'www-data' | expand | cut -c-$COLUMNS
4
  • 1
    ...and if you want your output colored by grep (as I do), you cut first and grep then.
    – DerMike
    Oct 7, 2011 at 8:31
  • And I added an alias in my ~/.bash_aliases file: alias cutt='cut -c -$COLUMNS'. Now I can just pipe to cutt ... Jul 3, 2014 at 11:05
  • 1
    This misbehaves if there are tabs in the output. Any suggestions? One options is to convert tabs to spaces first, but it would be nice to avoid this, in case we wish to preserves tabs for later in the pipeline. Nov 13, 2014 at 13:14
  • 2
    I found expand and edited the answer to include it. It corrects for tab Nov 13, 2014 at 19:47
3

You can crop the output using cut. e.g.

ps aux | grep -v 'www-data' | cut -c1-${COLUMNS}

where ${COLUMNS} provides the current width of the terminal. The resize command can be used to re-generate the current width:

$ resize
COLUMNS=80;
LINES=24;
export COLUMNS LINES;

You could, if you wanted to automate this, wrap this up in a script nowrap:

#!/bin/bash

eval "export $(resize | grep 'COLUMNS=')"
cut -c1-${COLUMNS} -
3

And in addition to what nagul said, you can use in bash:

tput cols

to get the width:

COLUMNS=$(tput cols)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .