Associative Array Group And Count

Group and count items using a bash associative array as a frequency map with iteration over sorted keys.

BashCli Tooling

Code

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

declare -A counts

while read -r line; do
  ((counts["$line"]++))
done < input.txt

for key in "${!counts[@]}"; do
  printf "%s\t%d\n" "$key" "${counts[$key]}"
done | sort -t$'\t' -k2 -rn

What the code does

Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.

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

Statements that matter most here

while read -r line; do
  ((counts["$line"]++))
for key in "${!counts[@]}"; do
  printf "%s\t%d\n" "$key" "${counts[$key]}"
done | sort -t$'\t' -k2 -rn

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?
`declare` must be available on the PATH environment variable; everything else is shell built-in syntax.