The following simple example shows how to use awk '{ printf "%-10s %s\n", $1, $2 }' mail-listThis command prints the names of the people ( $ awk '{ printf "%-10s %s\n", $1, $2 }' mail-list-| Amelia 555-5553-| Anthony 555-3412-| Becky 555-7685-| Bill 555-1675-| Broderick 555-0542-| Camilla 555-2912-| Fabius 555-1234-| Julie 555-6699-| Martin 555-6480-| Samuel 555-3430-| Jean-Paul 555-2127In this case, the phone numbers had to be printed as strings because the numbers are separated by dashes. 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 a awk 'BEGIN { print "Name Number" print "---- ------" } { printf "%-10s %s\n", $1, $2 }' mail-listThe preceding example mixes awk 'BEGIN { printf "%-10s %s\n", "Name", "Number" printf "%-10s %s\n", "----", "------" } { printf "%-10s %s\n", $1, $2 }' mail-listPrinting 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 }' mail-list |
HOWTO‎ > ‎
