Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Here is the data:

D 2
B 2
A 2

When I run this command:

sort -k2,2 file

it outputs:

A 2
B 2
D 2

My question is that when I specify only the second column -k2,2, why is it that it sorts by the first column as well? Since all of the values of the second column are the same, it should leave it as it is.

share|improve this question
[Semi-OT]: FYI, a sort that preserves the input order when sort keys match is known in computer science as stable sort. Often sorts aren't stable, because many non-stable sort algorithms are quicker or simpler. Not the case here, but knowing the CS term makes the manpage docs for the -s option understandable & findable. – derobert Feb 7 '13 at 21:11
up vote 25 down vote accepted

That's the last resort comparison. When comparing two lines, if all the keys compare equal, then as a last resort, a basic string comparison of the whole lines is performed (-r still applies but not the other options). That behavior is specified by POSIX:

Except when the -u option is specified, lines that otherwise compare equal shall be ordered as if none of the options -d, -f, -i, -n, or -k were present (but with -r still in effect, if it was specified) and with all bytes in the lines significant to the comparison. The order in which lines that still compare equal are written is unspecified.

With GNU sort, that last-resort comparison can be disabled with the -s (for stable) option.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.