Skip to main content

Command Palette

Search for a command to run...

Bash sort command

Updated
•2 min read•View as Markdown

In this article, we will use bash sort command to sort by multiple fields.

Let's delve into the first example.

Here's content of text file I named this.txt.

5000|1|god                                                                      
5000|3|son                                                                      
5000|2|spirit                                                                   
1000|2|spirit                                                                   
100|1|god                                                                       
100|3|son                                                                       
100|2|spirit

Let's sort by first field then by second field. Since they are consecutive we can just do

$ sort -k1,2 -t '|' this.txt 
1000|2|spirit
100|1|god
100|2|spirit
100|3|son
5000|1|god
5000|2|spirit
5000|3|son

instead of sort -k1,1 -k2,2 -t '|' this txt. In fact, if first and second fields were not numbers we could just sort by the entire line: sort -t '|' this.txt.

But take a closer look at how first field was sorted. This is incorrect as 1000 comes before 100. We need to denote that they are numbers.

Like this

$ sort -k1,2n -t '|' this.txt 
100|1|god
100|2|spirit
100|3|son
1000|2|spirit
5000|1|god
5000|2|spirit
5000|3|son

Now they are correctly sorted.

Actually, I lied. You can actually sort by entire line.

$ sort -n -t'|' this.txt 
100|1|god
100|2|spirit
100|3|son
1000|2|spirit
5000|1|god
5000|2|spirit
5000|3|son

Just force numerical sort (-n) and it all worked out.

Now another example.

Here is text people.txt

Simon Strange 62
Pete Brown 37
Mark Brown 46
Stefan Heinz 52
Tony Bedford 50
John Strange 51
Fred Bloggs 22
James Bedford 21
Emily Bedford 18
Ana Villamor 44
Alice Villamor 50
Francis Chepstow 56
$ sort -k2,2 -k1,1 people.txt 
Emily Bedford 18
James Bedford 21
Tony Bedford 50
Fred Bloggs 22
Mark Brown 46
Pete Brown 37
Francis Chepstow 56
Stefan Heinz 52
John Strange 51
Simon Strange 62
Alice Villamor 50
Ana Villamor 44

Here couldn't do -k1,2 because we wanted to sort first by last name then by first name. Because fields to be sorted are out of order we cant do sort people.txt either.

More from this blog

Linux and Web

31 posts