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
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
Sorts the lines in 'names.txt' alphabetically and prints the result to standard output.
Sort numerically
Sorts the lines in 'numbers.txt' numerically.
Sort in reverse order
Sorts the lines in 'data.txt' in reverse (descending) alphabetical order.
Sort unique lines
Sorts the lines in 'list.txt' and removes duplicate lines, printing only unique entries.
Sort by a specific field (e.g., comma-separated)
Sorts 'data.csv' based on the second comma-separated field.
Sort and save to a new file
Sorts 'input.txt' and saves the sorted output to 'sorted_output.txt'.