0Pricing
Linux Command Line & Bash Scripting Mastery · Lesson

awk Functions, printf Formatting, and Report Generation

Define user functions and use printf to emit polished tabular reports from raw data streams.

Why Functions and printf Matter in awk

As your awk programs grow from one-liners to multi-step pipelines, two features become essential: user-defined functions and printf formatting.

Functions let you encapsulate reusable logic — a percentage calculator, a string trimmer, a unit converter — so you write it once and call it anywhere in the same program. printf lets you control exactly how output looks: column widths, decimal places, padding, and alignment.

Together they transform raw log lines into polished, readable reports that engineers and managers can act on.

  • Functions reduce duplication and make programs testable in isolation.
  • printf aligns data into fixed-width columns so reports stay legible even with varying input lengths.
  • Both features work in POSIX awk, gawk, and mawk — no extensions needed.

Defining a User Function in awk

A user function is declared with the function keyword, before or after any pattern-action rules. The syntax is:

function name(param1, param2,    local1, local2) {
    # body
    return value
}

A key awk idiom: local variables are simply extra parameters with extra whitespace before them. There is no local keyword — the convention of extra spaces signals that those parameters are locals, not arguments the caller passes.

  • All variables not declared as parameters are global by default.
  • Functions can call themselves recursively.
  • return is optional; without it the function returns an empty string.
#!/usr/bin/env bash
# Demonstrate a simple awk user function
echo '10 3
7 0
100 4' | awk '
function divide(a, b,    result) {
    if (b == 0) return "ERR"
    result = a / b
    return result
}
{
    print $1 "/" $2 " = " divide($1, $2)
}
'

All lessons in this course

  1. Records, Fields, and Custom Separators in awk
  2. Patterns, Ranges, and BEGIN/END Blocks
  3. Aggregation with awk Arrays and Grouping
  4. awk Functions, printf Formatting, and Report Generation
← Back to Linux Command Line & Bash Scripting Mastery