sort Command

The sort command in Linux is used to sort lines of text files or standard input. It can sort alphabetically, numerically, by month, and more, making it a powerful tool for data manipulation and analysis.

Syntax

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

Description

sort writes sorted concatenation of all FILE(s) to standard output. With no FILE, or when FILE is -, read standard input.

Common uses include:

  • Sorting lines alphabetically or numerically
  • Removing duplicate lines
  • Merging sorted files
  • Sorting by specific fields

Common Options

Option Description
-b, --ignore-leading-blanks Ignore leading blanks
-d, --dictionary-order Consider only blanks and alphanumeric characters
-f, --ignore-case Fold lower case to upper case characters
-g, --general-numeric-sort Compare according to general numerical value
-i, --ignore-nonprinting Consider only printable characters
-M, --month-sort Compare (unknown) < (January, February, ...)
-n, --numeric-sort Compare according to string numerical value
-r, --reverse Reverse the result of comparisons
-u, --unique With -c, check for strict uniqueness; without -c, output only the first of an equal run

Examples

Sort a file alphabetically

sort names.txt

Sorts the lines in 'names.txt' alphabetically and prints the result to standard output.

Sort numerically

sort -n numbers.txt

Sorts the lines in 'numbers.txt' numerically.

Sort in reverse order

sort -r data.txt

Sorts the lines in 'data.txt' in reverse (descending) alphabetical order.

Sort unique lines

sort -u list.txt

Sorts the lines in 'list.txt' and removes duplicate lines, printing only unique entries.

Sort by a specific field (e.g., comma-separated)

sort -t',' -k2 data.csv

Sorts 'data.csv' based on the second comma-separated field.

Sort and save to a new file

sort input.txt > sorted_output.txt

Sorts 'input.txt' and saves the sorted output to 'sorted_output.txt'.

See also