The sort command is used to sort the lines of a text file in ascending or descending order, or sort as per a specified key. The sort command arranges the lines in a file. Common sort command options are provided in the table.
Option | Description |
---|---|
-k{column numbers} | Specify field values. For example, -k2 indicates the second field. |
-n | Compare and sort lines based on the string numerical value. |
-r | Sort fields in descending order. By default, the fields are sorted in ascending order. |
-t{delimiter} | Separate one field from another. |
If you encounter the below error while running the sort command:
sort: command not found
you may try installing the below package as per your choice of distribution:
Distribution | Command |
---|---|
OS X | brew install coreutils |
Debian | apt-get install coreutils |
Ubuntu | apt-get install coreutils |
Alpine | apk add coreutils |
Arch Linux | pacman -S coreutils |
Kali Linux | apt-get install coreutils |
CentOS | yum install coreutils |
Fedora | dnf install coreutils |
Raspbian | apt-get install coreutils |
Syntax
The syntax of the sort command is:
# sort [options] {file names}
sort Command Examples
1. Sort a file in ascending order:
# sort path/to/file
2. Sort a file in descending order:
# sort --reverse path/to/file
3. Sort a file in case-insensitive way:
# sort --ignore-case path/to/file
4. Sort a file using numeric rather than alphabetic order:
# sort --numeric-sort path/to/file
5. Sort `/etc/passwd` by the 3rd field of each line numerically, using “:” as a field separator:
# sort --field-separator=: --key=3n /etc/passwd
6. Sort a file preserving only unique lines:
# sort --unique path/to/file
7. Sort a file, printing the output to the specified output file (can be used to sort a file in-place):
# sort --output=path/to/file path/to/file
8. Sort numbers with exponents:
# sort --general-numeric-sort path/to/file