Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit output to the terminal width

Tags:

bash

shell

When I use pstree I see that lines only go up to the terminal width (that is, no word wrap), but when I grep the output, it does wrap. What function is it using to change this behavior?

bash$ pstree
\--= 76211 _spotlight /System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata.framework/Versions/A/Support/mdworker MDSImporte
bash$ pstree | grep MDSImporte
\--= 76211 _spotlight /System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata.framework/Versions/A/Support/mdworker MDSImporterWorker com.apple.Spotlight.ImporterWorker.89
like image 749
nachocab Avatar asked Jul 25 '11 18:07

nachocab


2 Answers

pstree seems to think that you don't want wrapped output, thus it asks the terminal about its width and outputs just as much. top and ps behave similar.

You can avoid this by piping the output through cat:

pstree | cat

Edit: Ah, I see that you want not avoid it, but add the chopping.

An easy way is piping the output of your command through less -S (or less --chop-long-lines, more verbosely). (You may want to combine this with some other options, see the manual page, depending on your preferences).

pstree | grep MDSImporte | less -SEX

will show your the lines cut off at terminal size.

like image 134
Paŭlo Ebermann Avatar answered Oct 13 '22 01:10

Paŭlo Ebermann


pstree must be checking to see if it's writing to a terminal, and if so it queries the terminal for its column width and then limits the output accordingly. You could do something similar:

WIDTH=`stty size | cut -d ' ' -f 2`            # Get terminal's character width
pstree | grep MDSImporte | cut -c 1-${WIDTH}   # Chop output after WIDTH chars

Other utilities (e.g. less) can do this for you but may have other side-effects (e.g. prompting you to press the space bar after each page of output).

Also...

If you're asking how you could determine whether a script is writing to a terminal, file, or pipe, you could do this:

[ -t 1 ] && WIDTH=`stty size | cut -d ' ' -f 2`
pstree | grep MDSImporte | cut -c 1-${WIDTH}

This will set WIDTH if and only if standard output is a terminal. If it is, it'll limit the output to WIDTH characters (by invoking cut -c 1-80, say). If it's not, it won't limit the output (because cut -c 1- does nothing).

like image 20
Rob Davis Avatar answered Oct 13 '22 03:10

Rob Davis