Awk Field Aggregate And Report

Use awk to aggregate fields by key with conditional logic and formatted output for log analysis.

BashCli Tooling

Code

bashsnippet
17 lines
#!/usr/bin/env bash
set -euo pipefail

awk '
{
  key = $1
  value = $2
  sum[key] += value
  count[key]++
}
END {
  for (k in sum) {
    printf "%-20s total=%10d count=%6d avg=%.2f\n", \
      k, sum[k], count[k], sum[k] / count[k]
  }
}
' access.log | sort

Inside the snippet

The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.

The work is delegated to awk, key and value, chained through 1 pipe so each stage’s output feeds the next.

Core lines under the microscope

for (k in sum) {
' access.log | sort

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`awk`, `key`, `value` must be available on the PATH environment variable; everything else is shell built-in syntax.