Introduction
The sort
command is a tool for sorting file contents and printing the result in standard output. Reordering a file's contents numerically or alphabetically and arranging information in ascending or descending order improves readability.
In this tutorial, you will learn to use the Linux sort
command and see useful examples.
Prerequisites
- A system running Linux.
- Access to a terminal.
Linux sort Syntax
The sort
command has the following syntax:
sort [options] filename
Note: While the sort
command arranges data in the specified order, the grep
command displays or hides the specified information. Follow our tutorial to learn to use the grep command.
Running the sort
command without [options]
outputs the file's contents and applies the default sorting rules for the current locale.
The main rules are:
- Lines starting with a number go before the lines beginning with a letter, arranged in ascending order (1-10).
- Lines starting with letters are sorted in ascending alphabetical order (A-Z).
For example, the following file has multiple random lines:
Run sort
to arrange the file's contents in the default manner:
The example above shows how the sort
command arranges lines by default when no options are specified.
Note: The sort
command assumes the data is in ASCII format. The locale settings affect the character's encoding and sorting. For example, to sort uppercase letters first, set the LC_ALL
environment variable to the POSIX locale (C
). Run LC_ALL=C
to set the environment variable.
Linux sort Options
Specify an option to change the sort
command sorting rules. The most used options are listed in the table below:
Short option form | Long option form | Description |
---|---|---|
-b | --ignore-leading-blanks | Causes sort to ignore leading blanks. |
-d | --dictionary-order | Causes sort to consider only blanks and alphanumeric characters. |
-f | --ignore-case | Ignores the default case sorting rule and changes all lowercase letters to uppercase before comparison. |
/ | --files0-from=F | Reads input from the files specified by NUL -terminated names in the specified F file. If F is - , sort reads names from standard input. |
-M | --month-sort | Sorts lines according to months (Jan-Dec). |
-h | --human-numeric-sort | Compares human-readable numbers (e.g., 2K 1G). |
-n | --numeric-sort | Compares data according to string numerical values. |
-R | --random-sort | Sorts data by a random hash of keys but groups identical keys together. |
/ | --random-source=FILE | Gets random bytes from the specified FILE . |
-r | --reverse | Reverses the comparison results. |
/ | --sort=WORD | Sort data according to the specified WORD : general-numeric -g , human-numeric -h , month -M , numeric -n , random -R , version -V . |
-c | --check, --check=diagnose-first | Checks if the input is already sorted but doesn't sort it. |
/ | --debug | Annotates the part of the line used for sorting. |
-k | --key=KEYDEF | Sort data using the specified KEYDEF , which gives the key location and type. |
-m | --merge | Causes sort to merge already sorted files. |
-o | --output=FILE | Redirects the output to FILE instead of printing it in standard output. |
-t | --field-separator=SEP | Uses the specified SEP separator instead of non-blank to blank transition. |
-z | --zero-terminated | Causes sort to use NUL as the line delimiter instead of the newline character. |
/ | --help | Displays the help file with full options list and exits. |
/ | --version | Outputs the program version and exits. |
Linux sort Examples
Below are examples of using the sort
command to arrange file contents in different ways.
Example 1: Save Output to File
The sort
command only displays a file's contents after arranging them, but it doesn't change the file. However, the -o
option allows you to save the sort
command output to a file.
For example, the following command sorts the data in the default.txt file and saves the output to the sorted.txt file:
sort -o sorted.txt default.txt
Running cat outputs the new file's contents.
Another way to save the sort
command output is to redirect the output to a file:
sort default.txt > sorted.txt
Example 2: Check for Sorting in File
Specify the -c
option to check if a file's contents have already been sorted. If the contents are already sorted, there's no output from the sort
command.
However, when sort
finds an unsorted line, it outputs a message reporting the first line is out of place.
For example:
sort -c default.txt
The command outputs a message reporting the number and contents of the first unsorted line.
Example 3: Sort Multiple Files
There are two ways to sort multiple files:
1. List filenames as arguments separated with a space.
Sort multiple files simultaneously by specifying the respective file names as arguments, separated by whitespace. The files' contents are joined together, sorted, and printed in standard output.
For example:
sort default1.txt default2.txt
The command concatenates, sorts, and prints both files' contents.
2. Pipe the find
command output to sort
.
Another way to sort multiple files simultaneously is to pipe the find command output to sort
and use the --files0-from=
option in the sort
command.
Specify the -print0
option in find
to end file name with the NUL
character and ensure the program properly reads the file list.
For example:
find -name "default?.txt" -print0 | sort --files0-from=-
The example above concatenates and sorts the default1.txt and default2.txt files.
Example 4: Sort by Fields
By default, sort
compares the entire line's contents and decides how to sort it. To compare according to a data subset, specify which fields to compare using the -k
option.
The -k
option takes the following syntax:
-k [ FStart [ .CStart ] ] [ Modifier ] [ , [ FEnd [ .Cend ] ][ Modifier ] ]
FStart
. The beginning of the line.CStart
. The first column in the field.Fend
. The end of the line.CEnd
. The last column of the field.
The sort key includes all characters beginning with the field specified by the FStart
variable and the column specified by the CStart
variable. The key ends with the field specified by FEnd
and the column specified by CEnd
.
Not specifying Fend
assumes the line's last character as the end. Without specifying CEnd
, the last character in the FEnd
field is assumed.
If there is any space between the fields, sort
considers them as separate fields.
For example, the lines in the following file contain three fields:
Sort the data based on the second field by running:
sort -k 2,2 school.txt
The command sorts the data according to the second field and ignores the first field.
Note: By default, sort
assumes that fields are separated by whitespace. If there are multiple blank characters, sort considers them a part of the following field for sorting purposes. Specify the -b
option to ignore any leading blank characters.
Example 5: Sort in Reverse Order
Use the -r
option to sort the data in reverse order, i.e., in reverse alphabetical order or highest to lowest numbers.
For example, the following file is sorted with the default sorting rules:
sort default.txt
Specifying the -r
option reverses the sorting order:
sort -r default.txt
Example 6: Remove Duplicate Entries
The -u
option allows sort
to remove duplicate entries from a file. For example, the following file has several duplicate entries:
Specifying the -u
option sorts the data and removes the duplicate lines:
sort -u test.txt
Example 7: Sort by Months
Specify the -M
option to arrange data according to months listed in a file.
To demonstrate sorting by months, create a file populated by the ls command output:
ls -l > month-sorting.txt
Sort the data from the ls -l
output by months by running the following command:
sort -Mk6 month-sorting.txt
The command sorts the file contents based on the sixth field containing the file creation month.
Example 8: Randomly Sort Data
Use the -R
option to randomly arrange data without applying any sorting criteria.
For example, the following file contains several lines sorted numerically:
Mix up the line order with the following command:
sort -R ordered.txt
The output shows that data is now randomly sorted.
Example 9: Specify a Delimiter
sort
separates fields in a line using whitespace (spaces or tabs) as field delimiters. Specify the -t
option to change the field delimiter to a different character.
For example, the following file contains multiple fields, including a person's name, job title, and place of residence:
Sorting the file by place of residence without changing the delimiter doesn't work because some cities have a space in the middle of their name. The space makes sort
interpret the city name as two fields instead of one.
Change the delimiter to a comma (,
) to properly sort the file's contents:
sort -t, -k4 school.txt
Changing the delimiter produces the desired output.
Example 10: Sort a Stream Output
Another way to supply input to the sort
command is to use the pipe (|
) operator. Piping into sort
allows it to arrange another command's output and, optionally, save the results into a file.
The following example shows how to pipe the ls
command output into sort
and arrange the contents by file size:
ls -l /home/$USER | sort -nk5
The -nk5
options specify numeric sorting in the fifth field.
Conclusion
This tutorial showed how to use the sort
command to rearrange a file's contents effectively. Easily arrange large data sets in an ascending or descending order using sort
.
For more Linux commands and a downloadable PDF cheat sheet, refer to our Linux commands cheat sheet.