Bash使用第一行计算输出以将空格添加到后续行

时间:2012-06-26 17:24:22

标签: bash printf

我这里有这段代码

printf '$request1 = "select * from whatever where this = that and active = 1 order by something asc";\n' 
| perl -pe 's/select/SELECT/gi ; s/from/\n   FROM/gi ; s/where/\n      WHERE/gi ; s/and/\n      AND/gi ; s/order by/\n         ORDER BY/gi ; s/asc/ASC/gi ; s/desc/DESC/gi ;' 
| awk '{gsub(/\r/,"");printf "%s\n%d",$0,length($0)}'

它产生这样的输出

$request1 = "SELECT * 
22   FROM whatever 
17      WHERE this = that 
24      AND active = 1 
21         ORDER BY something ASC";

我想取第一行(22)的计数,并在每个额外的行中添加该空白量。

1 个答案:

答案 0 :(得分:0)

假设您不想打印数字,请将AWK命令更改为:

awk 'NR == 1 {pad = length($0); print} NR > 1 {gsub(/\r/,""); printf "%*s%s\n", pad, " ", $0}'

输出:

$request1 = "SELECT * 
                         FROM whatever 
                            WHERE this = that 
                            AND active = 1 
                               ORDER BY something ASC";