How can I limit the output to the width of the terminal

When I use pstree , I see that the lines only go up to the width of the terminal (i.e. there is no word pstree ), but when I grep output, it ends. What function does he use 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 
+7
source share
3 answers

pstree does pstree seem like you want wrapped output, so it asks the terminal about its width and outputs the same amount. top and ps behave similarly.

You can avoid this by sending output via cat :

 pstree | cat 

Edit: Ah, I see that you do not want to avoid this, but add chopping.

A simple way is to output the command of your command via less -S (or less --chop-long-lines , in more detail). (You can combine this with some other options, see the manual page, depending on your preference).

 pstree | grep MDSImporte | less -SEX 

will show your lines cut off from the size of the terminal.

+10
source

pstree needs to check if it writes the terminal, and if it requests the terminal for its column width, and then limits the output accordingly. You can do something like this:

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

Other utilities (such as less ) may do this for you, but may have other side effects (for example, asking you to press the space bar after each page of output).

Also...

If you ask how you can determine if a script is writing to a terminal, file or channel, you can 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 so, it will limit the output to WIDTH characters (by calling cut -c 1-80 , say). If this is not the case, this will not limit the output (because cut -c 1- does nothing).

+3
source

it checks if the output is a terminal.

other programs perform similar actions:

 grep --color=auto ls --color=auto 
+1
source

All Articles