bash printf格式-避免长行换行

时间:2018-06-24 12:48:08

标签: bash printf

输入样本:

line1:word word
line2:word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word word
line3:word word word

当我用printf格式化时,孤独行被包裹-如何避免?

$ cat input_test|while IFS=: read a b;do printf "%-10s %-3s %s\n" "$a" ":" "$b";done
line1      :   word word
line2      :   word word word word word word word word word word word word word word word word word word word word word 
word word word word word word word word word word word word word word word word word word word word word word word word 
word word word word word word word word word
line3      :   word word word

如果第二列(用冒号分隔)长于终端预期输出中可能出现的行数:

line1      :   word word
line2      :   word word word word word word word word word word word word word word word word word 
               word word word word word word word word word word word word word word word word word 
               word word word word word word word word word word word word word word word word word 
               word word word
line3      :   word word word

2 个答案:

答案 0 :(得分:1)

您可以使用column

cat input_test | column -c100 -s: -o'      :   ' -t -W2

可悲的是,这将在输出中输出额外的':':

line1      :   word word
line2      :   word word word word word word word word word word word word word word word word word 
           :   word word word word word word word word word word word word word word word word word 
           :   word word word word word word word word word word word word word word word word word 
           :   word word word
line3      :   word word word

我们可以使用sed将其删除:

cat input_test | column -c100 -s: -o'      :   ' -t -W2 | sed 's/^           :   /               /'

答案 1 :(得分:1)

如果您对awk满意,那么下面的内容可能会对您有所帮助,还不确定第二行在拆分后是否始终需要3列?以下操作不会做到这一点。

awk -v s1="\t" '{sub(/:/,"      :     ",$1)}NF>10{;for(i=10;i<=NF;i+=10){$i=$i ORS s1 s1}} 1' Input_file

输出如下。

line1      :     word word
line2      :     word word word word word word word word word word
                 word word word word word word word word word word
                 word word word word word word word word word word
                 word word word word word word word word word word
                 word word word word word word word word word word
                 word word word word
line3      :     word word word

您也可以根据需要根据列数更改NF>10。如果您要更改它,请也将循环的数字(无论是10还是10)也更改为该数字。