Home·Terminal commands

sort

Text processing

Usage

sort -k 2 -n [file]

Sorts lines; without -n it compares them as text so 10 comes before 9, and the locale decides the order unless you put LC_ALL=C in front.

Common flags

FlagMeaning
-nCompare as numbers, not as text
-hCompare human sizes such as 2K and 1G
-rReverse the order
-kSort by a field, as in -k2
-tSet the field separator
-uDrop duplicate lines
-fIgnore case
-oWrite the result to a file, even back onto the input

Examples

du -sh * | sort -h

Biggest directory last.

sort -t, -k2 -n data.csv

Numeric sort on the second column.

sort -u names.txt

Sorted, with duplicates gone.

These were built to be piped together. Three joined commands are usually shorter than one that does everything.

How to read this

  • Square brackets [ ] mark a part you may leave out.
  • An ellipsis … means you can list more than one.
  • Flags are case-sensitive — in some commands -r and -R do different things.

Questions

Q. What does sort do?

Sorts lines; without -n it compares them as text so 10 comes before 9, and the locale decides the order unless you put LC_ALL=C in front.

Q. How do I type it?

sort -k 2 -n [file] — square brackets mark the parts you can leave out.

Q. How many flags are worth knowing?

8 are listed here; the full set is in man sort. This command sits under Text processing.

Related commands

man page: man sort