0

I'm trying to understand an existing script used in our project with the sort command

sort -t= -nr -k3 nos 

Where nos is a file with whitespace and numbers, for this example: 997 998 999 1000

The output is

999
998
997
1000

What I don't understand is why 1000 appears last. I suspect it is because of the argument -k3 when there is only key for each entry but I can't find anything in the documentation to say how it behaves when the specified key position doesn't exist.

Up until 4-digit numbers were included in the file this gave the expected result of sorting the numbers descending numerically.

  • What does your input file really look like? It appears to be a single line in your question, but the sort command indicates the existence of at least 2 equals-signs. Also, the output (4 lines) couldn't be generated from 1 line of input. – Jeff Schaller Oct 18 '18 at 17:04
  • 3
    It's the part that says Finally, as a last resort when all keys compare equal, sort compares entire lines as if no ordering options other than --reverse (-r) were specified. which is exactly what you get there i.e. the same as sort -r – don_crissti Oct 18 '18 at 17:04
3

When you specify a sorting field that does not exist, the sorting key will be empty for each comparison that sort does. This means that the keys will compare equal, always. This triggers a part of the standard specification of sort that says that the whole line should be used as the sorting key and that none of the options -d, -f, -i, -n, or -k remains in effect.

This in turn means that the command will be identical in effect to

sort -r nos

which does a reverse lexicographical sorting of the data (the -t= has no effect here). 997 precedes 1000 in reverse lexicographical order since 9 orders before 1.


The relevant bit from the POSIX standard:

-k keydef

[...]

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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