Back to the command reference

sort

ShellFundamentals In simulator In real Linux

Sort lines of text

Name: sort

You can practise it right away in the simulator, and use it in real Linux mode too.

Description

sort sorts all input lines. By default it compares characters according to the locale; -n compares numbers, -h human sizes like 2K or 1G, -k a chosen field, and -t sets the field separator.

sort has to read all input before printing anything. It pairs with uniq, which only handles adjacent duplicates.

Syntax

sort [OPTION]... [FILE]...

Common options

-n / --numeric-sortCompare as numbers
-h / --human-numeric-sortCompare human-readable sizes like 2K, 1G
-V / --version-sortSort version numbers (1.9 before 1.10)
-M / --month-sortSort by month name (Jan < Feb < …)
-r / --reverseReverse the order
-k / --key KEYDEFSort by field N, e.g. -k2
-t / --field-separator SEPField separator, e.g. -t,
-u / --uniqueOutput only unique lines
-f / --ignore-caseIgnore case
-s / --stableStable: lines that compare equal keep their order
-R / --random-sortShuffle (equal lines stay together)
-o / --output FILEWrite the result to FILE (it may be the input: sort -o f f is safe)
-c / --checkOnly check whether it is sorted

Examples

  • $ sort data/fruits.txt

    Sort alphabetically

    Explain
  • $ sort -u data/fruits.txt

    Sort and remove duplicates

    Explain
  • $ sort -t, -k3 -n data/scores.csv

    Sort a CSV numerically by the 3rd field

    Explain

Related