2

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?

4

2 回答 2

3

如果您希望标题与列对齐,您可以使用恰当命名的column实用程序(BSD 扩展,但它也随大多数 Linux 发行版提供)。要将现有文本重新格式化为对齐的列,请使用该-t选项。

您可以使用复合语句插入列标题:

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

或者:

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

(无论您发现哪个更具可读性。)

请注意,标题中可能没有空格,数据元素也可能没有。如果您的数据不是用空格分隔的,您可以使用该-s选项指定不同的分隔符;请记住为您的标题使用相同的分隔符。

column左对齐所有列,因此数字列看起来不像您希望的那样好。

于 2013-08-09T06:49:04.433 回答
1

您可以在 shell 中使用块来插入另一个命令,并使用它在另一个命令的输出之前或之后插入行,例如 grep 之前的 echo:

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

为了让您在脚本中更轻松,您可以使用以下表单:

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

在 awk 中,您可以使用 BEGIN:

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

和/或 END 添加尾行:

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

当然,如果你有两个以上的命令,你可以只使用最后一个表格

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

或者

command | command | awk 'BEGIN { print "header"; } /something/;'
于 2013-08-09T06:11:11.583 回答