user3850633
user3850633

Reputation: 23

gnu/unix sort numerical only using first column?

With regular strings, if the first field matches, we sort by the next field and so on, and things work as we expect.

echo -e 'a c\na b' | sort  #regular string sort
a b
a c

With numbers, if the first field matches, we…switch to string sort on subsequent fields? Why? I would think it would compare each field numerically.

echo -e '1 22\n1 3' | sort -n   #numeric sort
1 22
1 3

FYI, using sort (GNU coreutils) 5.97 on RHEL 5.5.

What am I missing here? I know I can use -k to pick the field I want to sort on, but that drastically reduces the flexibility of input allowed, as it requires the user to know the numbers of fields.

Thanks!

Upvotes: 2

Views: 202

Answers (1)

user2404501
user2404501

Reputation:

Sadly you haven't missed anything. This apparently simple task - split lines into fields and then sort numerically on all of them - can't be done by the unix sort program. You just have to figure out how many columns there are and name them all individually as keys.

What's happening when you specify -n no other options is that the whole line is being passed to the "convert string to number" routine, which converts the number at the start of the line and ignores the rest. The split into fields is not done at all.

Your first example, without -n, is also doing whole-line comparison. It's not comparing "a" to "a" then "b" to "c". It's comparing "a b" to "a c".

Upvotes: 1

Related Questions