Programming with awk

The printf statement

awk's printf statement is essentially the same as that in C except that the * format specifier is not supported. The printf statement has the general form

   printf format, expr[1], expr[2], . . ., expr[n]
where format is a string that contains both information to be printed and specifications on what conversions are to be performed on the expressions in the argument list, as in ``awk printf conversion characters''. Each specification begins with a %, ends with a letter that determines the conversion, and may include:

Left-justify expression in its field.

Pad field to this width as needed; fields that begin with a leading 0 are padded with zeros.

Specify maximum string width or digits to right of decimal point.

``awk printf conversion characters'' lists the printf conversion characters.

awk printf conversion characters

Character Prints expression as
c single character
d decimal number
e [-]d.ddddddE[+-]dd
f [-]ddd.dddddd
g e or f conversion, whichever is shorter, with nonsignificant zeros suppressed
o unsigned octal number
s string
x unsigned hexadecimal number
% print a %; no argument is converted

Below are some examples of printf statements along with the corresponding output:

   printf "%d", 99/2	49
   printf "%e", 99/2	4.950000e+01
   printf "%f", 99/2	49.500000
   printf "%6.2f", 99/2	49.50
   printf "%g", 99/2	49.5
   printf "%o", 99	143
   printf "%06o", 99	000143
   printf "%x", 99	63
   printf "|%s|", "January"	|January|
   printf "|%10s|", "January"	|   January|
   printf "|%-10s|", "January"	|January   |
   printf "|%.3s|", "January"	|Jan|
   printf "|%10.3s|", "January"	|       Jan|
   printf "|%-10.3s|", "January"	|Jan       |
   printf "%%"	%
The default output format of numbers is %.6g; this can be changed by assigning a new value to OFMT. OFMT also controls the conversion of numeric values to strings for concatenation and creation of array subscripts.
Next topic: Output to files
Previous topic: Output separators

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004