awk 'BEGIN { printf ("Hello, world\n") }'
The main difference that you will notice at the outset is
that, unlike print, printf does not
automatically supply a newline. You must specify it
explicitly as "\n".
The full syntax of the printf statement has two parts:
printf ( format-expression [, arguments] )
%-width.precision format-specifier
The width of the output field is a numeric value.
When you specify a field width, the contents of the field
will be right-justified by default. You must specify
"-" to get left-justification. Thus, "%-20s" outputs
a string left-justified in a field 20 characters wide. If
the string is less than 20 characters, the field will be
padded with whitespace to fill.
In the following examples,
a "|" is output to indicate the actual width of the field.
The first example right-justifies the text:
printf("|%10s|\n", "hello")
It produces:
| hello|
The next example left-justifies the text:
printf("|%-10s|\n", "hello")
It produces:
|hello |
You can specify both the width and precision dynamically,
via values in the printf or sprintf argument list.
You do this by specifying asterisks, instead of literal values.
printf("%*.*g\n", 5, 3, myvar);
In this example, the width is 5, the precision is 3, and the value
to print will come from myvar.
Using the full syntax of the format expression
can solve the problem with filesum
of getting fields and headings properly aligned.
One reason we output the file size before the filename was that
the fields had a greater chance of aligning themselves
if they were output in that order.
The solution that printf offers us is the ability to
fix the width of output fields; therefore, each field begins
in the same column.
Let's rearrange the output fields in the filesum report.
We want a minimum field width so that the second field begins
at the same position. You specify
the field width place between the % and the conversion
specification. "%-15s" specifies a minimum field width
of 15 characters in which
the value is left-justified. "%10d", without the hyphen,
is right-justified, which is what we want for a decimal value.
printf("%-15s\t%10d\n", $9, $5) # print filename and size
This will produce a report in which the data
is aligned in columns and the numbers are right-justified.
Look at how the printf statement
is used in the END action:
printf("Total: %d bytes (%d files)\n", sum, filenum)
The column header in the BEGIN rule is also changed appropriately.
With the use of the printf statement, filesum
now produces the following output:
$ filesum g*
FILE BYTES
g 23
gawk 2237
gawk.mail 1171
gawk.test 74
gawkro 264
gfilesum 610
grades 64
grades.awk 231
grepscript 6
Total: 4680 bytes (9 files)