Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท AWK Basics

AWK print, printf and Output Redirection

Format AWK output precisely: print versus printf, format specifiers, widths and alignment, redirecting to files, piping to commands such as sort, and using close().

An AWK program that computes the right numbers but prints them badly is only half useful. In this lesson you will learn the two output statements, print for quick output and printf for exact control, how to align columns into neat tables, and how to send output to files or to other commands from inside the program.

print

print writes its arguments separated by OFS (a space) and ends with ORS (a newline). Without arguments it prints $0. Arguments joined with a space (no comma) are concatenated.

Bash print basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

printf: formatted output

printf format, arg1, arg2, ... prints according to a format string. Unlike print, it adds no newline unless you write \n. Each % specifier consumes one argument.

Specifier Meaning Example Result
%d or %i integer printf "%d", 3.9 3
%s string printf "%s", "hi" hi
%f fixed decimal printf "%.2f", 3.14159 3.14
%e scientific printf "%.2e", 12345 1.23e+04
%g shortest of %f/%e printf "%g", 0.0001 0.0001
%x, %X, %o hex, octal printf "%x", 255 ff
%c character (number gives its character) printf "%c", 65 A
%% a literal percent sign %
Bash Format specifiers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

%d truncates toward zero rather than rounding. To round, use %.0f (which rounds half to even in the C library) or int(x + 0.5).

Width, alignment and padding

After the % you can put flags, a minimum width, and a precision (.n):

  • %10s: right-aligned in 10 columns; %-10s: left-aligned.
  • %05d: zero-padded to width 5.
  • %+d: always show the sign.
  • %.3s: at most 3 characters of the string.
  • %*d: take the width from an argument (not supported by every awk).
Bash A formatted table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The item name can contain spaces (orange juice), so the program rebuilds it from the fields between the first and the last two. %-14s pads names to 14 characters, %6.2f shows the price with two decimals in 6 columns, and so on. Columns line up because every row uses the same format.

Bash Headings, rules and zero padding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

sprintf works like printf but returns the string instead of printing it, which is how you build text to store, compare, or use as an array key.

Common printf mistakes

  1. Forgetting \n: printf "%s", $1 glues everything on one line.
  2. Passing too few arguments: printf "%s %s\n", $1 prints an empty second value (some awks warn).
  3. User data as the format: printf $0 breaks if the data contains %. Write printf "%s\n", $0.
  4. Using %d for very large numbers or non-integers where you wanted rounding.

Output redirection

You can send print and printf output to files, inside the program:

Form Effect
print > "file" write to file, truncating it the first time only in this run
print >> "file" append to file
`print "command"`
print > "/dev/stderr" write to standard error (supported by most awks)

The first time a file is opened with >, it is emptied; afterwards in the same run, all > writes append to it. The file stays open until you close() it or AWK exits.

Bash Splitting a file by key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The parentheses around $1 ".out" matter: the expression after > should be wrapped to avoid ambiguity with concatenation. This idiom splits one file into many, one per key.

Inside print, an unparenthesized > is a redirection, not a comparison. print $1 > $2 writes $1 to a file named after $2. To print a comparison result, write print ($1 > $2).

Piping to a command

print | "sort" sends all output of that statement to one sort process, which writes when it is closed or when awk finishes. It is the easy way to sort the results of an AWK report without leaving the program.

Bash Sorting output from inside awk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

close("sort -rn") waits for the sort to finish and flush its output. Without it, "end of ranking" could appear before the sorted lines, because sort only writes when its input ends. The string you pass to close must be exactly the same as the command string.

You can also read from a command with "cmd" | getline; that belongs with input handling in later lessons.

system()

system("command") runs a shell command and returns its exit status. Flush pending output first if the order matters, because AWK buffers its output when it is not a terminal.

Bash system() and ordering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

fflush() is common (it is in POSIX 2024 and every awk we know of), but old awks may lack it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does printf "%-10s|", "ab" print?

    The minus flag left-aligns the text in a 10-character field; printf adds no newline.
  2. 2. What is the difference between print $1 $2 and print $1, $2?

    Without a comma the two values are joined; with a comma AWK puts OFS (a space) between them.
  3. 3. What does print $1 > "out.txt" do?

    > after print is an output redirection.
  4. 4. Why call close("sort -rn") after piping output to it?

    sort outputs only once its input ends; closing the pipe ends its input and waits for it.
  5. 5. What does printf "%d", 3.9 print?

    %d converts to an integer by truncating the fractional part.

Summary

  • print is quick; printf gives exact control with %d %s %f %e %x %c %%, widths, - alignment, zero padding and precision.
  • sprintf builds a formatted string; always put user data in arguments, not in the format.
  • >, >> and | redirect print/printf to files or commands; wrap the target in parentheses and close() when order matters.
  • An unparenthesized > in print is a redirection, not a comparison.

Next: AWK String and Math Functions