B>As can be seen in Table 7-1, most of the escape sequences are treated identically, whether in the format string, or in argument strings printed with %b. However, \c and \0 ddd are only valid for use with %b, and \ ddd is only interpreted in the format string. (We have to admit that the occasional wine cooler is a handy accessory to have when first learning some of the Unix utility idiosyncracies.)
As may be surmised, it is the format specifiers that give printf its power and flexibility. The format specification letters are given in Table 7-2.
Table 7-2. printf format specifiers
Item
Description
%b
The corresponding argument is treated as a string containing escape sequences to be processed. See Table 7-1, earlier in this section.
%c
ASCII character. Print the first character of the corresponding argument.
%d, %i
Decimal integer.
%e
Floating-point format ([-]d.precision e[+-]dd).
%E
Floating-point format ([-]d.precision E[+-]dd).
%f
Floating-point format ([-]ddd.precision).
%g
%e or %f conversion, whichever is shorter, with trailing zeros removed.
%G
%E or %f conversion, whichever is shorter, with trailing zeros removed.
%o
Unsigned octal value.
%s
String.
%u
Unsigned decimal value.
%x
Unsigned hexadecimal number. Use a-f for 10 to 15.
%X
Unsigned hexadecimal number. Use A-F for 10 to 15.
%%
Literal %.
The floating-point formats, %e, %E, %f, %g, and %G, "need not be supported," according to the POSIX standard. This is because awk supports floating-point arithmetic and has its own printf statement. Thus, a shell program needing to do formatted printing of floating-point values can use a small awk program to do so. However, the printf commands built into bash, ksh93, and zsh do support the floating-point formats.
The printf command can be used to specify the width and alignment of output fields. To accomplish this, a format expression can take three optional modifiers following the % and preceding the format specifier:
%flags 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 are right-justified by default. You must specify a flag of - to get left justification. (The rest of the flags are discussed shortly.) Thus, "%-20s" outputs a left-justified string in a field 20 characters wide. If the string is less than 20 characters, the field is padded with spaces 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
| hello|
The next example left-justifies the text:
$ printf "|%-10s|\n" hello
|hello |
The precision modifier is optional. For decimal or floating-point values, it controls the number of digits that appear in the result. For string values, it controls the maximum number of characters from the string that will be printed. The precise meaning