Name

printf

Synopsis

printf [format [, expressions]]

Description

Formatted print statement. Expressions or variables can be formatted according to instructions in the format argument. The number of expressions must correspond to the number specified in the format sections.

format follows the conventions of the C-language printf statement. Here are a few of the most common formats:

%s

A string.

%d

A decimal number.

% n.m f

A floating point number. n = total number of digits; m = number of digits after decimal point.

%[-] nc

n specifies minimum field length for format type c, while - left-justifies value in field; otherwise, value is right-justified.

Field widths are adjustable. For example, %3.2f limits a floating-point number to a total width of three digits, with two digits after the decimal point.

format also can contain embedded escape sequences, \n (newline) and \t (tab) being the most common. Spaces and literal text can be placed in the format argument by quoting the entire argument. If there are multiple expressions to be printed, multiple formats should be specified.

Example

Using the script:

                     {printf ("The sum on line %s is %d.\n", NR, $1+$2)}

the following input line:

                     5   5

produces this output, followed by a newline:

The sum on line 1 is 10.

Get Linux in a Nutshell, Third 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.