printf Formats

Format specifiers for printf and sprintf have the following form:

%[posn$][flag][width][.precision]letter

The control letter is required. The format-conversion control letters are given in the following table.

Character

Description

c

ASCII character.

d

Decimal integer.

i

Decimal integer (added in POSIX).

e

Floating-point format ([-]d.precisione[+−]dd).

E

Floating-point format ([-]d.precisionE[+−]dd).

f

Floating-point format ([-]ddd.precision).

g

e or f conversion, whichever is shortest, with trailing zeros removed.

G

E or f conversion, whichever is shortest, with trailing zeros removed.

o

Unsigned octal value.

s

String.

u

Unsigned decimal value.

x

Unsigned hexadecimal number. Uses a-f for 10 to 15.

X

Unsigned hexadecimal number. Uses A-F for 10 to 15.

%

Literal %.

gawk allows you to provide a positional specifier after the % (posn$). A positional specifier is an integer count followed by a $. The count indicates which argument to use at that point. Counts start at one and don’t include the format string. This feature is primarily for use in producing translations of format strings. For example:

$ gawk 'BEGIN { printf "%2$s, %1$s\n", "world", "hello" }'
hello, world

The optional flag is one of the following.

Character

Description

-

Left-justify the formatted value within the field.

space

Prefix positive values with a space and negative values with a minus.

+

Always prefix numeric values with a sign, even if the value is positive.

#

Use an alternate form: %o has a preceding 0; %x and %X are prefixed with 0x and ...

Get Linux in a Nutshell, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.