WolfNZO WolfNZO - 2 months ago 10
Bash Question

sort multiple columns numerically

I always wondered how

works when ordering multiple columns according to their numerical values. For example:

echo -e " 2 3 \n 1 2 \n 2 10" | sort -n


1 2
2 10
2 3

and so does
sort -g
. If I want to order numerically the second column as well, the only solution I came up with is:

echo -e " 2 3 \n 1 2 \n 2 10" | sort -k1n -k2n

which produces the desired output:

1 2
2 3
2 10

Someone could please explain this behavior and tell if a simpler solution exists?


The POSIX specification for sort says:

Restrict the sort key to an initial numeric string, consisting of optional <blank> characters, optional minus-sign, and zero or more digits with an optional radix character and thousands separators (as defined in the current locale), which shall be sorted by arithmetic value. An empty digit string shall be treated as zero. Leading zeros and signs on zeros shall not affect ordering.

This is essentially the same as saying -k1n,1. If you want to sort by multiple columns numerically, you must say so:

sort -k1n,1 -k2n,2 …

Be cautious about omitting the 'field end' after the commas.