
The sort command without any options sorts the contents of a file. The ls command with the --sort=size or -S option can be used to sort a listing of files.
By default, the sort command will sort a file numerically from 0 to 9 and then alphabetically from a to z.
~]# sort example.txt
1 How are you today?
Beautiful
Hello world
It is a good day today
Reverse sort
The -r or --reverse option sorts the file in reverse order. The file is sorted alphabetically from z to a and then numerically from 9 to 0.
~]# sort -r example.txt
It is a good day today
Hello world
Beautiful
1 How are you today?
Numeric sort
The -n or --numeric-sort option can be used to sort a file numerically.
~]# sort -n example.txt
5
17
32
47
97
105
Take for example the following numeric sort.
~]# sort -n example.txt
0 Barack
50 George
60 Ronald
100 Bill
The sort check command will state that the file is not sorted. Likewise, the join command will state "file1 not sorted".
~]# sort -c example.txt
sort: example.txt:4: disorder: 100 Bill
Adding the -n option will not produce any stdour or stderr, meaning the file is numerically sorted. However, this may not be desired, as the join command may fail to join a numerically sorted file.
~]# sort -c -n example.txt
The sort command with no options will sort the file as follows.
~]# sort example.txt
0 Barack
100 Bill
50 George
60 Ronald
And now the sort check command will not produce any stdout or stderr, meaning the file is sorted. The join command will be able to join the file.
~]# sort -c example.txt
Sort the current file
The -o or --output option can be used to sort and then overwrite the current file, so that you do not need to create a second, sorted file.
~]# sort /path/to/example.txt --output /path/to/example.txt
You may want to also use the -u or --unique flag to update the file to only contain one line for each string of unique text.
~]# sort --unique --output /path/to/file1.txt /path/to/file1.txt
Determine if a file is sorted
The -c or --check option will determine if the file is sorted. If the file is not sorted, "disorder" will be displayed. If the file is sorted, there will be no output.
//Sorted example
~]# sort -c example.txt
//Not Sorted example
~]# sort -c example.txt
sort: example.txt:2: disorder
Months
The -M or --month-sort option will sort the file by Month.
~]# cat -M example.txt
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
Sort a specific column
By default, sort will sort on column 1 (first name in this example). The -k or --key option can be used to specify the column to be sorted. For example, --key 2 sorts by the second column, which is last name in this example.
~]# cat example.txt | sort --key 2
Cleveland Brown
Brian Griffin
Peter Griffin
Stewey Griffin
Glenn Quagmire
Did you find this article helpful?
If so, consider buying me a coffee over at