December 5, 2026

sort and uniq: Counting Duplicate Lines, and Why uniq Alone Misses Most of Them

Mixed colored buttons sorted into neat piles by color on a table

A six-line file holding apple, banana, apple, apple, cherry, banana went through uniq and came out as five lines: apple banana apple cherry banana. Two duplicates survived. uniq didn’t malfunction. It only compares each line with the one directly above it, so it only collapses duplicates that sit next to each other. That one rule is why the standard Unix idiom is sort | uniq, and it’s behind most of the confusing results people get when counting things in logs. Every command below was run with GNU coreutils 9.4, and the output shown is what came back.

Video: CodeLucky on YouTube

uniq only sees neighbors

The adjacency rule

The GNU uniq manual says it plainly: the input doesn’t need to be sorted, but “repeated input lines are detected only if they are adjacent.” In the fruit file, the second apple was next to the first, so uniq merged them. The third apple came after banana, so as far as uniq was concerned, it was new.

Sort first

Sorting puts every copy of a line next to every other copy:

sort fruit.txt | uniq        # apple banana cherry
sort -u fruit.txt            # apple banana cherry

Both produced the same three lines. The uniq manual itself points to sort -u for removing duplicates that aren’t adjacent. The sort manual describes -u as outputting “only the first of a sequence of lines that compare equal.” For plain de-duplication, sort -u is one process instead of two. When counts are needed, uniq is the tool.

Clipboard, pencil, and pen on a wooden surface

Counting with uniq -c

How many of each

The -c option, per the manual, prints “the number of times each line occurred along with the line”:

sort fruit.txt | uniq -c
      3 apple
      2 banana
      1 cherry

The top-N pattern

Add a numeric reverse sort and the most common lines float to the top:

sort fruit.txt | uniq -c | sort -rn

This pipeline, sort, count, sort again, is one of the most reused one-liners in Unix. The first sort groups identical lines. uniq -c counts each group. sort -rn orders by that count, highest first. Adding | head -10 gives a top-ten list.

Only the duplicates, or only the loners

Two more options split the data in useful ways. -d is described as “Discard lines that are not repeated,” and -u keeps only lines that never repeat:

sort fruit.txt | uniq -d    # apple banana
sort fruit.txt | uniq -u    # cherry

uniq -d is a fast way to find duplicate entries in a list that’s supposed to be unique, such as usernames, order numbers or email addresses on a mailing list.

How many distinct lines

Sometimes the question is just how many different values exist, not how often each appears. sort -u file | wc -l answers it. On the two-million-line test file of IP addresses described below, it returned 1000, the exact number of distinct addresses the generator could produce, in about 0.4 seconds. The same count from uniq needs the sort first: sort file | uniq | wc -l. Leave out the sort and the number is simply wrong, often by a large margin, with nothing in the output to warn that it’s wrong.

A real job: counting a web log

Top client addresses

A small access log with nine requests, one per line in the format IP METHOD PATH STATUS, was used for testing. cut pulls the first field, the IP address:

cut -d' ' -f1 access.log | sort | uniq -c | sort -rn
      3 10.0.0.9
      3 10.0.0.5
      2 10.0.0.7
      1 10.0.0.3

Status codes

Pulling the fourth field instead, with awk '{print $4}', counted response codes:

      5 200
      3 401
      1 404

Three 401s, all from 10.0.0.9 requesting /login, is exactly the kind of pattern this pipeline is good at surfacing. On a real server with millions of lines, the same command shows which addresses are hammering a login page or which URLs are returning errors, in a few seconds.

The awk alternative

awk can count without sorting first, using an associative array:

awk '{c[$1]++} END{for(k in c) print c[k], k}' access.log | sort -rn

It produced the same four counts. On a two-million-line test file of IP addresses, it finished in about 196 milliseconds, while sort | uniq -c | sort -rn took about 540. Both returned the same top entry, 2146 10.0.1.31. The awk version holds one counter per distinct value in memory, so it’s quickest when the number of distinct lines is small, a thousand addresses in this test. The sort pipeline copes with inputs too large for memory: GNU sort writes temporary files, and its manual’s -T option exists to “store temporary files” in a chosen directory for a large sort.

Someone checking items off a checklist

Sorting traps that break the count

Text order versus number order

By default, sort compares text character by character:

printf '10\n9\n100\n2\n' | sort      # 10 100 2 9
printf '10\n9\n100\n2\n' | sort -n   # 2 9 10 100

“10” sorts before “9” as text for the same reason “apple” comes before “banana”: the first character decides. The sort manual describes -n as “Sort numerically.” That’s why the top-N pipeline uses sort -rn, not sort -r: the counts from uniq -c are numbers, and text sorting would put a count of 9 above a count of 10.

Human-readable sizes

Output from du -h and ls -lh uses suffixes like K, M and G. Plain -n reads only the leading number:

printf '2G\n512M\n1.5G\n900K\n' | sort -n   # 1.5G 2G 512M 900K
printf '2G\n512M\n1.5G\n900K\n' | sort -h   # 900K 512M 1.5G 2G

The manual says -h sorts by numeric sign and then “by SI suffix.” Only -h got the real order.

Sorting by a column

-k picks which field to sort on, and -t sets the separator. The manual describes -t as using a given character “as the field separator when finding the sort keys”:

printf 'ada 31\nbob 9\ncal 120\n' | sort -k2 -n
# bob 9 | ada 31 | cal 120
printf 'ada,31\nbob,9\ncal,120\n' | sort -t, -k2,2n
# bob,9 | ada,31 | cal,120

Without -n, sort -k2 on the same data gave cal 120 | ada 31 | bob 9, text order again. In a CSV, -k2,2 limits the key to the second field alone; a bare -k2 runs from field two to the end of the line.

Invisible differences

Case

Apple, apple and APPLE are three different lines to sort and uniq:

printf 'Apple\napple\nAPPLE\n' | sort | uniq -c
      1 APPLE
      1 Apple
      1 apple

The uniq manual’s -i option is described as “Ignore differences in case when comparing lines.” Paired with sort -f, which folds case when sorting, sort -f | uniq -ci counted all three as one line with a count of 3.

Trailing spaces

Two lines that look identical on screen may not be. printf 'apple\napple \n' put a space after the second one, and uniq -c counted them separately. Piping the output through cat -A, which marks line ends with $, showed why:

      1 apple$
      1 apple $

Log files and copy-pasted lists often carry stray spaces or Windows \r line endings. When a count looks too high, cat -A is the quickest way to see what the characters really are. sed 's/[[:space:]]*$//' strips trailing whitespace before counting; on a test with apple and a tab-ended banana, cat -A afterward showed clean apple$ and banana$.

Locale

The sort manual warns that with a non-POSIX locale, “sort may produce output that is sorted differently than you’re accustomed to,” and recommends setting LC_ALL to C in that case. For scripts where the exact order matters, LC_ALL=C sort gives plain byte order on every machine. In the test environment, which only had C locales installed, both LC_ALL=C and C.UTF-8 sorted b B a A as A B a b, uppercase first.

Red apples and sliced lemon on a brown paper bag

Keeping the original order

When sorting is not acceptable

sort -u and sort | uniq both reorder the data. Sometimes the original order matters, such as a list of steps or a history file. This awk one-liner removes duplicates while keeping each line’s first appearance in place:

awk '!seen[$0]++' fruit.txt     # apple banana cherry

It prints a line only the first time it’s seen. For the fruit file, the output happened to match the sorted order, since the first appearances were already alphabetical. On a list of cherry, apple, cherry, it returned cherry apple, while sort -u returned apple cherry.

Skipping fields and characters

uniq can also ignore parts of each line. The manual lists -f n to “Skip n fields on each line before checking for uniqueness” and -s n to “Skip n characters.” That handles logs where every line starts with a different timestamp: uniq -f 1 compares everything after the first field, so the same message at different times counts as a repeat. Three log lines, two reading disk full with different timestamps and one reading ok, came out as 2 2026-01-01T10 disk full and 1 2026-01-01T12 ok. uniq shows the first line of each group, so the timestamp displayed is the earliest one.

Sources

  • GNU Coreutils manual, “uniq invocation”: https://www.gnu.org/software/coreutils/manual/html_node/uniq-invocation.html
  • GNU Coreutils manual, “sort invocation”: https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html

920 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *