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

35,309

Solution 1

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

sort -k1,1 -k2n

Solution 2

It is almost correct. Try this:

sort -k1,1 -k2,2n

Solution 3

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
Share:
35,309
Necto
Author by

Necto

Updated on January 27, 2020

Comments

  • Necto
    Necto over 4 years

    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