Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort by first column textually and then by the second numerically with 'sort'?

I'm trying to sort the following file:

a 2
b 1
a 10

I need to get:

a 2
a 10
b 1

I know about the -kPOS[opts] option, and try to use it:

sort -k1 -k2n file

but this command gives me only:

a 10
a 2
b 1

So it sorts by the first column, but no by the second. Running just sort -k2n file sorts by the second column.

b 1
a 2
a 10

How could I sort it by two columns?

Edit:

sort (GNU coreutils) 5.93

like image 243
Necto Avatar asked Jan 31 '13 11:01

Necto


3 Answers

You have to terminate the primary key, otherwise, sort uses all the fields starting from the given one:

sort -k1,1 -k2n
like image 144
choroba Avatar answered Nov 20 '22 20:11

choroba


It is almost correct. Try this:

sort -k1,1 -k2,2n
like image 28
Magnus Gustavsson Avatar answered Nov 20 '22 19:11

Magnus Gustavsson


If you have GNU sort sort then you can do a version sort:

$ sort -V file
a 2
a 10
b 1

Option:

-V, --version-sort          natural sort of (version) numbers within text

The nice thing about version sorting is it will work regardless of columns:

$ cat file
a2
b1
a10

$ sort -V file
a2
a10
b1
like image 6
Chris Seymour Avatar answered Nov 20 '22 19:11

Chris Seymour