Organize a file using the SORT command in Linux

Home > Search > Linux commands
  by

Forward sort

The sort command without any options sorts the contents of a file. The file is sorted numerically from 0 to 9 and then alphabetically from a to z.

[user1@server1 ]# sort file1
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.

[user1@server1 ]# sort -r file1
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 file1
5
17
32
47
97
105

 

Take for example the following numeric sort.

~]# sort -n file1.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 file1.txt
sort: file1.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 file1.txt

 

The sort command with no options will sort the file as follows.

~]# sort file1.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 file1.txt

 

 


Sort the current file

The -o 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/file.txt -o /path/to/file.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
[user1@server1 ]# sort -c file1

//Not Sorted example
[user1@server1 ]# sort -c file1
sort: file1:2: disorder

 


Months

The -M or --month-sort option will sort the file by Month.

[user1@server1 ]# cat -M months.txt
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec

 


Sort a specific field

The -k option can be used to sort by another field. For example, -k 2 sorts by the second field, which is last name in this example.

[user1@server1 ]# cat names.txt | sort -k 2
Cleveland Brown
Brian Griffin
Peter Griffin
Stewey Griffin
Glenn Quagmire

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments