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.
More on Text processing: grep, sed, awk, cut, sort, uniq
What are the most useful `grep` flags?BeginnerWhat is the difference between basic, extended and Perl regular expressions in grep?IntermediateWhat are the core `sed` commands you use in automation?BeginnerWhy does `sed -i` behave differently on macOS and Linux?IntermediateHow do you use variables inside a `sed` expression safely?AdvancedWhat is the structure of an `awk` program?Beginner