Linux commands
Browse topics

Sorting and counting lines with sort and uniq

Version
unversioned
Review
Draft

Summary#

sort orders lines, and uniq collapses adjacent equal lines. Combine them to remove duplicates or count how often each line occurs.

Syntax#

sh
sort -u file
sort file | uniq -c | sort -k1,1nr
sort -t, -k2,2n file

-t sets the field separator, -k2,2n sorts numerically by the second field, and r reverses a key.

Example#

sh
(
  set -eu
  export LC_ALL=C
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  cd "$dir"
  printf '%s\n' 404 200 404 200 200 > status.txt

  echo '-- uniq alone'
  uniq status.txt
  echo '-- count each value, most frequent first'
  sort status.txt | uniq -c | sort -k1,1nr -k2,2n
  echo '-- text order, then numeric order'
  printf '%s\n' 10 9 100 | sort
  echo '--'
  printf '%s\n' 10 9 100 | sort -n
)

Expected output#

Text
-- uniq alone
404
200
404
200
-- count each value, most frequent first
      3 200
      2 404
-- text order, then numeric order
10
100
9
--
9
10
100

Common mistakes#

uniq compares only neighboring lines, so sort first unless you want to merge consecutive repeats. sort -n -u can collapse distinct lines such as 007 and 7 because their numeric keys compare equal. Use sort -n | uniq to retain both spellings. A key written as -k2 runs from field 2 to the end of the line; write -k2,2 to compare that field alone.

Version applicability#

This entry describes GNU coreutils sort and uniq. Collation depends on the locale; the example sets LC_ALL=C to compare bytes.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0