简体   繁体   English

在管道命令的输出中添加一行

[英]Adding a row to output of piped command

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. 现在,在命令的输出中,我想使用shell脚本在每个对话框的顶部添加一些标签或数据。

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? 实现此目的的简便方法是什么?

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). 如果您希望标题与列对齐,则可以使用恰当命名的column实用程序(BSD扩展,但大多数Linux发行版中都附带)。 To reformat existing text into aligned columns, use the -t option. 要将现有文本重新格式化为对齐的列,请使用-t选项。

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; 如果您的数据不是用空格隔开的,则可以使用-s选项指定其他定界符; 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. column左对齐所有列,因此数字列看起来并不像您希望的那样好。

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 eg echo before grep: 您可以在shell中使用块来插入另一个命令,并使用它在其他命令的输出之前或之后插入行,例如在grep之前执行echo:

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: 在awk中,您可以使用BEGIN:

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

And/or END to add tailing lines: 和/或END添加尾线:

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/;'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM