Interview Q&A / Linux & Shell

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you count how often each line appears, sorted from most to least?

SHORT ANSWER

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.

  • sort groups equal lines.
  • uniq -c prefixes counts.
  • sort -nr orders by that number, largest first (-n numeric, -r reverse).
  • head -3 keeps 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

bash
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.1

What 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.

#linux#text-processing#sort#uniq

Related questions

Practise more Linux & Shell questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Linux & Shell quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.