sort(1)
Sort lines of text files in ascending or descending order based on specified keys and options.
Synopsis
sort [OPTION]... [FILE]...Description
The sort command arranges lines of text input in a specified order. By default it sorts alphabetically in ascending order, comparing entire lines. You can sort by specific fields, reverse the order, perform numeric sorting, and remove duplicates.
If no files are specified, sort reads from standard input. Multiple files are concatenated before sorting, or you can use the -m option to merge pre-sorted files.
Common options
| Flag | What it does |
|---|---|
-n | Sort numerically instead of lexicographically; handles negative numbers and decimals correctly |
-r | Sort in reverse (descending) order |
-k POS1[,POS2] | Sort by specific field(s); POS format is F[.C][OPTS] where F is field number, C is character position |
-t SEP | Use SEP as field delimiter instead of whitespace |
-u | Remove duplicate lines (keep only unique lines) |
-f | Ignore case differences; fold lowercase to uppercase |
-o FILE | Write output to FILE instead of standard output |
-m | Merge already-sorted input files instead of sorting |
-c | Check if input is sorted; return 0 if sorted, 1 otherwise |
-V | Sort version numbers naturally (1.10 sorts after 1.9) |
-i | Ignore non-printable characters |
--random-sort | Shuffle lines randomly instead of sorting |
Examples
Sort lines in numbers.txt alphabetically and print to stdout
sort numbers.txtSort numerically; treats '9' as less than '10' (not '2' as in alphabetic sort)
sort -n numbers.txtSort in reverse (descending) order
sort -r numbers.txtSort /etc/passwd by UID (3rd field) numerically using colon as delimiter
sort -t: -k3 -n /etc/passwdSort and remove duplicate lines, keeping only unique entries
sort -u data.txtSort primarily by 2nd field, then by 1st field (multi-key sort)
sort -k2,2 -k1,1 file.txtCount occurrences of each line across multiple files and sort by frequency
cat file1.txt file2.txt | sort | uniq -c | sort -rnCheck if data.txt is sorted without printing output
sort -c -q data.txt && echo "File is sorted"