Interview Prep/Shell Scripting/Text processing: grep, sed, awk, cut, sort, uniq

How do you count occurrences per key with `awk` associative arrays?

IntermediateConceptText processing: grep, sed, awk, cut, sort, uniq
Answer
# Requests per status code
awk '{count[$9]++} END {for (c in count) print c, count[c]}' access.log | sort -k2,2nr

# 5xx per upstream, and error ratio
awk '{total++; if ($9 ~ /^5/) err[$NF]++}
     END {for (u in err) printf "%s %d (%.2f%%)\n", u, err[u], 100*err[u]/total}' access.log

for (k in arr) order is unspecified; sort the output. One awk pass replaces grep | cut | sort | uniq -c chains and is far faster on multi-GB logs.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Text processing: grep, sed, awk, cut, sort, uniq