Format Output of bash into columns

Alexey Fadyushin fab at s-tunnel.com
Sat Nov 27 14:41:54 UTC 2004



Mike Vanecek wrote:
> On Fri, 26 Nov 2004 19:27:09 -0500, Anthony E. Greene wrote
> 
>>On 26-Nov-2004/17:37 -0600, Mike Vanecek <rh_list at mm-vanecek.cc> wrote:
>>
>>>I have looked through my books and googled ... Tried serveral things 
> 
> without
> 
>>>success ...
>>>
>>>I would like to run the output of a bash command that produces 1 field per
>>>line output through sort and then output in 3 columns. I have looked at
>>>printf, fmt, column, and so on.
>>>
>>>For example,
>>>
>>>rpm -qa | sort 2>&1 |  column -c 2 
>>>
>>>rpm -qa | sort |  column -c 2
>>>
>>>Or say I have a file with a list of sorted names, for example,
>>>[admin at www admin]$ rpm -qa | sort -o rpm.txt
>>>
>>>Then I want to output the file with
>>>
>>>column -c 2 rpm.txt
>>>
>>
>>#!/usr/bin/perl
>>#
>># Format STDIN into three tab-delimited columns
>>#
>>$colnum = 1;
>>while ($line = <STDIN>) {
>>  chomp $line;
>>  if ($colnum < 3) {
>>    print "$line	";  # The whitespace is a tab character.
>>  } else {
>>    print "$line\n";
>>  }
>>}
>>
>>You could get fancy using perl's formatting features, but this quick$
>>dirty should work for lines that are all of similar length, or for input
>>in an application that easily parses tab-delimited data.
>>
> 
> 
> Thank you for the script. Another solution that I stumbled upon is to use pr, 
> e.g.,
> 
> rpm -qa | sort | pr --columns 3 -at  type of thing.
> 
> It truncates the columns a bit, but ...
> 

To prevent truncation when using 'pr' you could use its option '-J' 
(columns will not be truncated, but there will be problems with 
alingment of columns) or explicitly specify the width of resulting 
output using '-W<number of chars>' (by default 'pr' output is 72 
characters wide).

For example:
rpm -qa | sort | pr --columns 3 -aT -J
or
rpm -qa | sort | pr --columns 3 -aT -W132

Alexey Fadyushin
Brainbench MVP for Linux
http://www.brainbench.com






More information about the redhat-list mailing list