z/OS UNIX System Services User's Guide
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


Formatting the output

z/OS UNIX System Services User's Guide
SA23-2279-00

The output of the program:
$1 == "Jim" { print "$", $4/52 }
is:
$ 1.92308
$ 0.192308
$ 1.34615
This output shows the amount of money per week that Jim spent on his hobbies. However, money amounts usually have only two digits after the decimal point. How can you change the program to make the money amounts appear more normal? The answer is to use the printf action instead of print. This lets you specify the format in which awk prints the output.
A printf action looks like this:
{ printf format-string, value, value, ... }
The format-string indicates the output format. The values are the data to be printed.
A format string contains two kinds of items:
  • Normal characters, which are just printed out as is
  • Placeholders, which awk replaces with values given later in the printf action
As an example, try running the following program on the hobbies file:
$2 == "bridge" { printf "%5s plays bridge\n", $1 }
awk prints:
  Jim plays bridge
Linda plays bridge
 Lori plays bridge
The format string:
"%5s plays bridge\n"
has one placeholder: %5s. When printf prints its output, replacing the placeholder with the value $1, which is the first field of the record being examined. The rest of the format string is just printed out as is.
Note: The format string ends in \n; for more information, see Escape sequences.

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014