Question

I have a piped command say

command1 | command2 | command3

or lets say something like

ps | grep "something" 

Now to the output of the command I would like to add to each coloumn some label or data to the top using shell script.

EDIT
In short this is what i want

InsertedLabel1   Inslabel2        Inslabel3
Data1frompipe     Data1frompipe     Data1frompipe
Data2frompipe    Data2frompipe     Data2frompipe

What is an easy way to acheive this?

Was it helpful?

Solution

If you want the headers to line up with the columns, you can use the aptly named column utility (a BSD extension, but it also comes with most Linux distros). To reformat existing text into aligned columns, use the -t option.

You can insert the column headers using a compound statement:

command1 | command2 | { echo Header1 Header2 Header3; command3 } | column -t

or:

{ echo Header1 Header2 Header3; command1 | command2 | command3 } | column -t

(whichever you find more readable.)

Note that the headers may not have spaces in them, and nor may the data-elements. If your data is not white-space separated, you can specify a different delimiter with the -s option; remember to use the same delimiter for your headers.

column left-justifies all columns, so numeric columns don't look as nice as you might want them to.

OTHER TIPS

You could use blocks in shells to insert another command and use it to insert lines before or after the output of the other command e.g. echo before grep:

ps | { echo "header"; grep "something"; }

To make it easier for you in a script you could use this form:

ps | {
    echo "header"
    grep "something"
    # possibly other echos here.
}

In awk you could use BEGIN:

ps | awk 'BEGIN { print "header"; } /something/;'

And/or END to add tailing lines:

ps | awk 'BEGIN { print "header"; } /something/; END { print "------"; }'

Of course if you have more than two commands you could just use the form on the last

command | command | { echo "header"; grep "something"; }

Or

command | command | awk 'BEGIN { print "header"; } /something/;'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top