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?
sort (GNU coreutils) 5.93
You have to terminate the primary key, otherwise, sort uses all the fields starting from the given one:
sort -k1,1 -k2n
It is almost correct. Try this:
sort -k1,1 -k2,2n
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With