Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท AWK Programs

printf and Formatted Reports in AWK

Use AWK printf to align columns, pad and round numbers, build headers and footers with BEGIN and END, draw text bar charts and write tidy tabular reports.

print is fine for quick output, but reports need control: right-aligned numbers, fixed-width names, two decimals, a header line, a total at the bottom. For that AWK has printf, which works like the C function you may know from the C tutorial or from shell scripts, and the BEGIN/END blocks give you a place for headers and footers.

This lesson turns raw rows into reports you would be happy to paste in an email or a README.

printf basics

printf format, arg1, arg2, ... prints exactly what the format says. Unlike print, it adds no newline and no separators, so you end the format with \n.

Spec Meaning
%s a string
%d or %i an integer (the value is truncated)
%f a decimal number, 6 places by default
%e scientific notation
%x, %o hexadecimal, octal
%c one character (a number is treated as a character code)
%% a literal percent sign

Between % and the letter you may add flags and sizes: %-10s left-aligns in 10 columns, %8.2f right-aligns a number in 8 columns with 2 decimals, %05d zero-pads, %+d always shows the sign, %.3s cuts a string to 3 characters, and %*d takes the width from an argument.

Bash Format specifiers in action

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.

Notice %d with 42.9 prints 42 (it truncates, it does not round) and %.0f rounds to even-ish according to the C library. If you need conventional rounding, use int(x + 0.5) for positive numbers.

The pattern is always the same: BEGIN prints the title and column headings, the main rule prints one formatted row per record while accumulating totals, and END prints the summary.

Bash An invoice report

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 "Desk lamp" has a space in its name, so $1 is not the whole name. The program uses a trick for variable-length leading text: the last two fields are the numbers ($(NF-1) and $NF) and everything before them is the name.

Text bar charts

printf has no "repeat" feature, but a short loop (or sprintf with gsub) draws a bar. Scaling by a constant keeps long bars on screen.

Bash A bar chart from counts

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.

Tables with a computed column width

Hard-coded widths break when the data changes. Do two passes in one program: first store rows and track the longest value, then print using %-*s.

Bash Auto-sized columns

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.

%-*s takes the width from the argument just before the string. A few AWKs do not support *; in that case build the format first with fmt = "| %-" w "s | %s\n" and call printf fmt, ....

Output control: OFS, ORS, redirection

  • OFS is put between print items separated by commas; ORS ends each print.
  • print > "file" writes to a file (truncated once, then appended for the rest of the run); >> appends to an existing file; | "command" pipes into a command, such as sort. Close with close("file") or close("cmd") when you are done, especially before reading the file back.
  • print > "/dev/stderr" sends diagnostics to standard error.
Bash Splitting output into files and piping to sort

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.

Common mistakes

  • Forgetting \n: all output ends up on one line.
  • Using %d for big numbers: some AWKs overflow past 2^31. Use %.0f for large counts and money in cents.
  • Passing too few arguments: printf "%s %s\n", $1 prints an empty value (or an error) for the missing one.
  • Putting parentheses wrongly with redirection: write print > ($2 ".txt"), because print > $2 ".txt" is ambiguous.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which format right-aligns a number in 8 columns with two decimals?

    The number before the dot is the minimum width (right-aligned unless you add -), the number after is the decimal places.
  2. 2. What does printf "%d", 42.9 print?

    %d converts to an integer by truncating, it does not round.
  3. 3. Where should a report's header and totals normally be printed?

    BEGIN runs before any input is read and END after the last record, which fits a header and a summary line.
  4. 4. Why call close("sort") after piping output to sort inside awk?

    Closing the pipe lets sort flush its sorted output at that moment, instead of when awk exits.

Summary

  • printf prints exactly the format, with no automatic newline.
  • Widths and flags (%-10s, %8.2f, %05d) align columns; %d truncates.
  • Use BEGIN for headers, the main rule for rows and totals, END for the summary.
  • Variable-length leading text can be rebuilt from $1..$(NF-2).
  • print > file, >> file and | "cmd" redirect output; close() finishes them.

Next: User-defined Functions and Recursion in AWK