sort (Sort File Contents)
The sort
command is used to sort the content of a file. The command is often used with standard output redirection to save the output in another file.
Sort the content of a file in the command line
If you don't redirect the output of the command to a file, the command line returns the output to itself.
For example, we assume that you have the sample_sort.txt file with the contents like the one below.
cat sample_sort.txt
banana
apple
orange
grapes
When you run the sort command for the sample_sort.txt file, the sorted contents will be shown in the command line shown below.
sort sample_sort.txt
apple
banana
grapes
orange
-r option: Reverse order
When you use the -r
option, the sorting order is reversed.
For example, using the same sample_sort.txt file, run the sort -r
command. The command line returns the list of items in a reverse alphabetical order as shown below.
sort -r sample_sort.txt
orange
grapes
banana
apple
Redirect the output to another file
The sort command won't change the content of the file. It just gives sorted output in the command line as standard output.
For example, you can confirm that the content of sample_sort.txt stays the same as the original one by running the cat
command.
cat sample_sort.txt
banana
apple
orange
grapes
To save the output in a file, you can use standard output redirection (refer to Chapter 5 Standard Input Output and Redirection). For example, you can run the command below to create a new file sample_sorted.txt with the sorted output.
sort sample_sort.txt > sample_sorted.txt
By running the cat
command, you can confirm that a new file is created with the sorted contents.
cat sample_sorted.txt
apple
banana
grapes
orange
IMPORTANT
When you use redirection for the sort
command, you cannot use the same file name for standard output. If you use the same file, the contents of the file will be erased.