BEGIN/END Blocks

Print header and footer around data
cat <<'EOF' > /tmp/demo.txt
nginx running 4821
postgres running 1337
redis stopped 0
haproxy running 27014
EOF
awk 'BEGIN{print "=== Report ==="} {print} END{print "=== End ==="}' /tmp/demo.txt
Initialize variables in BEGIN
printf '87.3\n34.8\n12.5\n99.1\n56.2\n' | awk 'BEGIN{sum=0; count=0} {sum+=$1; count++} END{print sum/count}'
Set separators in BEGIN
awk 'BEGIN{FS=":"; OFS="\t"} {print $1, $3}' /etc/passwd
Formatted user table from /etc/passwd
awk 'BEGIN{
    FS=":"
    printf "%-20s %-5s %s\n", "USERNAME", "UID", "SHELL"
    printf "%-20s %-5s %s\n", "--------", "---", "-----"
}
{printf "%-20s %-5s %s\n", $1, $3, $7}
END{
    printf "%-20s %-5s %s\n", "--------", "---", "-----"
    printf "%d users total\n", NR
}' /etc/passwd
Generate sequence with no input — awk as a generator
awk 'BEGIN{for(i=1; i<=10; i++) printf "Item %02d\n", i}'
Generate numbered list of hosts
cat <<'EOF' > /tmp/hosts.txt
web-proxy-01.internal
db-primary.internal
cache-redis.internal
app-node-03.internal
monitor.internal
EOF
awk '{printf "%3d. %s\n", NR, $0}' /tmp/hosts.txt
Summary report — count and aggregate in END block
ss -tn state established | awk 'NR>1 {
    split($5,a,":")
    ip[a[1]]++
    total++
}
END{
    printf "%-16s %s\n", "REMOTE IP", "CONNECTIONS"
    printf "%-16s %s\n", "---------", "-----------"
    for(i in ip) printf "%-16s %d\n", i, ip[i]
    printf "\nTotal: %d connections\n", total
}'