Linux sort
command is used for sorting file content in a particular order. It supports sorting of files alphabetically (ascending or descending), numerically, in reverse order, etc. We can also remove duplicate lines from the file. In this article, we’ll see different example usages of the Linux sort command.
When using the sort command
- Lines beginning with numbers or digits appear before lines with alphabets.
- Lines starting with lowercase letters will appear before lines beginning with the same letter but in uppercase.
Linux Sort command without any arguements
When sort
is used without any arguments, it arranges the contents of a text file in alphabetical order. In this example, we are using the text file fruits.txt
as shown below.
To sort in alphabetical order run:
# sort fruits.txt
Output
Sort with -r option
If you wish to sort a file in reverse order using sort command, use the -r
option. For instance, to reverse the order of the input file in our previous example, execute:
# sort -r fruits.txt
Output
Sort numerically
To sort a file in a numerical order, use the -n
attribute. In this example, we have a file digits.txt
as shown below
To sort this file numerically from the smallest value to the largest value execute the command
# sort -n digits.txt
Output
You can also use the -nr
option to reverse the order of the numerical results, i.e. sort from the largest to the smallest value
To demonstrate this, we will run the command:
# sort -nr digits.txt
Output
Sort with -o option
The -o
option allows the user to write the output of the file onto a new file. Using this option is just the same as redirecting the output to another file as shown:
# sort fruits.txt > newfile.txt
To write the output of a file to a new file using -o
option use the syntax
# sort -o newfile.txt filename.txt
For example,
# sort sorted_fruits.txt fruits.txt
Output
Sort with -u option
The -u
option is used to remove file duplicates in a text file while at the same time sorting text alphabetically.
In this example, we are going to use cars.txt
as shown below
As you can see, we have 2 duplicate car models: Toyota and Porsche.
To remove these duplicates and sort alphabetically, run
# sort -u cars.txt
Output
Sort with -k option
The -k
option sorts a table according to the column number. For instance, if you have a table with 2 columns, use -k -2n
option to sort the second column.
In this example, we have the text file bonus.txt
To sort the second column execute
# sort -k -2n bonus.txt
Output
Sort months with -M option
Use the -M
option to sort a file containing months in ascending order i.e { Jan , Feb, … Nov, Dec }
We have a file months.txt as shown below
To sort the months in order execute:
# sort -M months.txt
Check the version of sort command
To check the version od sort command run
$ sort --version
Output
More options in sort command
To acquaint yourself with more commands other than the ones we’ve covered, visit the sort man page
# man sort