printf
The following is a simple example of
how to use printf
to make an aligned table:
awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
This command
prints the names of the bulletin boards ($1
) in the file
BBS-list as a string of 10 characters that are left-justified. It also
prints the phone numbers ($2
) next on the line. This
produces an aligned two-column table of names and phone numbers,
as shown here:
$ awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list -| aardvark 555-5553 -| alpo-net 555-3412 -| barfly 555-7685 -| bites 555-1675 -| camelot 555-0542 -| core 555-2912 -| fooey 555-1234 -| foot 555-6699 -| macfoo 555-6480 -| sdace 555-3430 -| sabafoo 555-2127
In this case, the phone numbers had to be printed as strings because the numbers are separated by a dash. Printing the phone numbers as numbers would have produced just the first three digits: `555'. This would have been pretty confusing.
It wasn't necessary to specify a width for the phone numbers because they are last on their lines. They don't need to have spaces after them.
The table could be made to look even nicer by adding headings to the
tops of the columns. This is done using the BEGIN
pattern
(see BEGIN/END)
so that the headers are only printed once, at the beginning of
the awk program:
awk 'BEGIN { print "Name Number" print "---- ------" } { printf "%-10s %s\n", $1, $2 }' BBS-list
The above example mixed print
and printf
statements in
the same program. Using just printf
statements can produce the
same results:
awk 'BEGIN { printf "%-10s %s\n", "Name", "Number" printf "%-10s %s\n", "----", "------" } { printf "%-10s %s\n", $1, $2 }' BBS-list
Printing each column heading with the same format specification used for the column elements ensures that the headings are aligned just like the columns.
The fact that the same format specification is used three times can be emphasized by storing it in a variable, like this:
awk 'BEGIN { format = "%-10s %s\n" printf format, "Name", "Number" printf format, "----", "------" } { printf format, $1, $2 }' BBS-list
At this point, it would be a worthwhile exercise to use the
printf
statement to line up the headings and table data for the
inventory-shipped example that was covered earlier in the section
on the print
statement
(see Print).