Skip to content

Linux Sorting

Sorting

sort

Sorts lines in one or more files alphabetically (default) or numerically (-n).

Terminal window
sort input1.txt input2.txt > output.txt

Writes the sorted content of both files into output.txt.

Useful Options

  • -n → numeric sort
  • -r → reverse order
  • -u → unique (equivalent to sort | uniq)
  • -k → sort by column/field (e.g., sort -k2 file.txt)
  • -t → specify delimiter (e.g., sort -t, -k2 file.csv)

uniq

Removes adjacent duplicate lines (so usually combined with sort).

Terminal window
sort input.txt | uniq > output.txt

Produces a sorted file without duplicates.

Useful Options

  • -c → prefix lines by occurrence count
  • -d → show only duplicates
  • -u → show only unique lines

Example:

Terminal window
sort names.txt | uniq -c | sort -nr

Counts duplicate entries, then sorts results by frequency.


Comparison

sortOrder lines alphabetically/numericallysort -n scores.txt
uniqRemove duplicate adjacent linessort data.txt &#124 uniq