[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
printf
Formats A format specification can also include modifiers that can control how much of the item's value is printed, as well as how much space it gets. The modifiers come between the `%' and the format-control letter. We will use the bullet symbol "*" in the following examples to represent spaces in the output. Here are the possible modifiers, in the order in which they may appear:
N$
printf "%s %s\n", "don't", "panic" printf "%2$s %1$s\n", "panic", "don't" |
prints the famous friendly message twice.
At first glance, this feature doesn't seem to be of much use.
It is in fact a gawk
extension, intended for use in translating
messages at runtime.
See section Rearranging printf
Arguments,
which describes how and why to use positional specifiers.
For now, we will not use them.
-
printf "%-4s", "foo" |
prints `foo*'.
space
+
#
0
width
printf "%4s", "foo" |
prints `*foo'.
The value of width is a minimum width, not a maximum. If the item value requires more than width characters, it can be as wide as necessary. Thus, the following:
printf "%4s", "foobar" |
prints `foobar'.
Preceding the width with a minus sign causes the output to be padded with spaces on the right, instead of on the left.
.prec
%e
, %E
, %f
%g
, %G
%d
, %i
, %o
, %u
, %x
, %X
%s
Thus, the following:
printf "%.4s", "foobar" |
prints `foob'.
The C library printf
's dynamic width and prec
capability (for example, "%*.*s"
) is supported. Instead of
supplying explicit width and/or prec values in the format
string, they are passed in the argument list. For example:
w = 5 p = 3 s = "abcdefg" printf "%*.*s\n", w, p, s |
is exactly equivalent to:
s = "abcdefg" printf "%5.3s\n", s |
Both programs output `**abc'.
Earlier versions of awk
did not support this capability.
If you must use such a version, you may simulate this feature by using
concatenation to build up the format string, like so:
w = 5 p = 3 s = "abcdefg" printf "%" w "." p "s\n", s |
This is not particularly easy to read but it does work.
C programmers may be used to supplying additional
`l', `L', and `h'
modifiers in printf
format strings. These are not valid in awk
.
Most awk
implementations silently ignore these modifiers.
If `--lint' is provided on the command line
(see section Command-Line Options),
gawk
warns about their use. If `--posix' is supplied,
their use is a fatal error.
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |