C.W.K.
Stream
Lesson 07 of 10 · published

sort + uniq

~12 min · sort, uniq, frequency

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The pair that solves frequency questions

Whenever you ask "what's the most common X in this file/log/output?" the answer is sort | uniq -c | sort -rn. Memorize that incantation; it solves a class of questions.

sort flags

  • -n — numeric sort (10 after 9, not after 1).
  • -r — reverse.
  • -h — human-numeric (1K, 5M, 2G correctly).
  • -u — unique (skip duplicates inline; lighter than uniq).
  • -k 2 — sort by the second whitespace-separated field.
  • -t ',' — set delimiter to comma (CSV).

uniq flags

  • -c — prefix each line with its count.
  • -d — only show duplicates.
  • -u — only show non-duplicates.

Big gotcha: uniq only deduplicates adjacent lines. You almost always need sort | uniq, not just uniq alone.

The frequency one-liner

cat access.log | awk '{print $1}' | sort | uniq -c | sort -rn | head

Reads: take the first field of each log line (the IP), group identical ones together, count, sort by count descending, show top 10. That's a production-grade analytics query in one pipe.

Code

Top file extensions in a project·bash
find . -type f -name '*.*' | awk -F. '{print $NF}' \
  | sort | uniq -c | sort -rn | head
Largest dirs·bash
du -sh */ 2>/dev/null | sort -h | tail
# Or in size-of-output style
du -h --max-depth=1 . 2>/dev/null | sort -hr | head

External links

Exercise

Run history | awk '{print $2}' | sort | uniq -c | sort -rn | head -20. Find your top 20 commands. Then on a log file (or dmesg): grep -oE '\b[A-Z]+\b' | sort | uniq -c | sort -rn | head to see common all-caps tokens.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.