2

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!

1 Answer 1

1

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.