How do you count how often each line appears, sorted from most to least?
Sort the input, count duplicates with uniq -c, then sort numerically in reverse: sort file | uniq -c | sort -nr. uniq only compares adjacent lines, so the first sort is required. Add head to keep the top results.
Explain it simply
Suppose you have a log with one IP address per line and want the top visitors, like finding the most-ordered dish on a Zomato report.
uniq merges adjacent identical lines, and -c puts a count in front. Because it only compares neighbours, you must sort first so equal lines sit together.
Pipeline: sort ips.txt | uniq -c | sort -nr | head -3.
sortgroups equal lines.uniq -cprefixes counts.sort -nrorders by that number, largest first (-nnumeric,-rreverse).head -3keeps the top three.
Without -n, sort compares text, so "10" would come before "9". Related: sort -u removes duplicates in one step (without counts), and uniq -d shows only the lines that repeat.
Example
printf '10.0.0.5\n10.0.0.9\n10.0.0.5\n10.0.0.5\n10.0.0.9\n10.0.0.1\n' | sort | uniq -c | sort -nr
# 3 10.0.0.5
# 2 10.0.0.9
# 1 10.0.0.1What to say in the interview
"sort | uniq -c | sort -nr gives a frequency table. The first sort is needed because uniq only merges adjacent duplicates, and -n makes the second sort numeric. I add head for the top N."
Common mistakes
- Skipping the first sort, so uniq counts nothing correctly.
- Forgetting -n and getting 9 ranked above 10.