gawk: Printf Examples
1
1 5.5.4 Examples Using 'printf'
1 -----------------------------
1
1 The following simple example shows how to use 'printf' to make an
1 aligned table:
1
1 awk '{ printf "%-10s %s\n", $1, $2 }' mail-list
1
1 This command prints the names of the people ('$1') in the file
1 'mail-list' as a string of 10 characters that are left-justified. It
1 also prints the phone numbers ('$2') next on the line. This produces an
1 aligned two-column table of names and phone numbers, as shown here:
1
1 $ awk '{ printf "%-10s %s\n", $1, $2 }' mail-list
1 -| Amelia 555-5553
1 -| Anthony 555-3412
1 -| Becky 555-7685
1 -| Bill 555-1675
1 -| Broderick 555-0542
1 -| Camilla 555-2912
1 -| Fabius 555-1234
1 -| Julie 555-6699
1 -| Martin 555-6480
1 -| Samuel 555-3430
1 -| Jean-Paul 555-2127
1
1 In this case, the phone numbers had to be printed as strings because
1 the numbers are separated by dashes. Printing the phone numbers as
1 numbers would have produced just the first three digits: '555'. This
1 would have been pretty confusing.
1
1 It wasn't necessary to specify a width for the phone numbers because
1 they are last on their lines. They don't need to have spaces after
1 them.
1
1 The table could be made to look even nicer by adding headings to the
11 tops of the columns. This is done using a 'BEGIN' rule (⇒
BEGIN/END) so that the headers are only printed once, at the beginning
1 of the 'awk' program:
1
1 awk 'BEGIN { print "Name Number"
1 print "---- ------" }
1 { printf "%-10s %s\n", $1, $2 }' mail-list
1
1 The preceding example mixes 'print' and 'printf' statements in the
1 same program. Using just 'printf' statements can produce the same
1 results:
1
1 awk 'BEGIN { printf "%-10s %s\n", "Name", "Number"
1 printf "%-10s %s\n", "----", "------" }
1 { printf "%-10s %s\n", $1, $2 }' mail-list
1
1 Printing each column heading with the same format specification used for
1 the column elements ensures that the headings are aligned just like the
1 columns.
1
1 The fact that the same format specification is used three times can
1 be emphasized by storing it in a variable, like this:
1
1 awk 'BEGIN { format = "%-10s %s\n"
1 printf format, "Name", "Number"
1 printf format, "----", "------" }
1 { printf format, $1, $2 }' mail-list
1