How to align columns with awk

浪子不回头ぞ 提交于 2021-02-17 07:07:58

问题


I tried to execute below command:

ls -ltr | awk 'BEGIN { print "File\t\t\tOwner"} { print $9,"\t",$3} END {print "-DONE \n"}'

and getting following o/p

File                    Owner

inventory-shipped        root
BBB_list         root
marks    root
test_file        root
awkvars.out      root
1        root
t12      root
-DONE

How i can get o/p like

File                    Owner

inventory-shipped       root
BBB_list                root
marks                   root
test_file               root
awkvars.out             root
1                       root
t12                     root
-DONE       

回答1:


You need to use padding except for the last column. Since you have only 2 columns, the first will be enough.

When you use printf instead of print, you can print all the variables based on a template. The following examples print a string (%s) with a padding (24) on the right side (-24), so it becomes %-24s.

ls -ltr | awk 'BEGIN {printf "%-24s%s","File","Owner"} { printf "%-24s%s\n",$9,$3} END {print "-DONE \n"}'

For more information you can check this or this.



来源:https://stackoverflow.com/questions/51915642/how-to-align-columns-with-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!