Abhijeet Patil
Abhijeet Patil

Reputation: 21

How to align columns with awk

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       

Upvotes: 1

Views: 4200

Answers (1)

dereli
dereli

Reputation: 1864

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.

Upvotes: 7

Related Questions