2

I have a file:

$ cat file
1 c
8 a
1 b
5 f

I think the sort command in the beginning compares the first field of all lines and sorts them then for those lines have equal first fields and starts sorting again for second fields like this:

$sort file
1 b
1 c
5 f
8 a

I read about the difference between the options k 1 and k 1,1: with k 1 it is possible the sort key continues to the end of the line but with k 1,1 it should sort only the first field without considering other fields but:

$sort -k 1 file
1 b
1 c
5 f
8 a

$sort -k 1,1 file
1 b
1 c
5 f
8 a

Why are the outputs of sort = sort k 1 = sort k 1,1 equal?

I think the output of sort k 1,1 file should be

1 c 
1 b
5 f
8 a

If it is not correct please tell me what is my mistake and how can I get output like that?

7

From info sort

   Many options affect how ‘sort’ compares lines; if the results are
unexpected, try the ‘--debug’ option to see what happened.  A pair of
lines is compared as follows: ‘sort’ compares each pair of fields, in
the order specified on the command line, according to the associated
ordering options, until a difference is found or no fields are left.  If
no key fields are specified, ‘sort’ uses a default key of the entire
line.  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.  The ‘--stable’ (‘-s’) option disables this
“last-resort comparison” so that lines in which all fields compare equal
are left in their original relative order.  The ‘--unique’ (‘-u’) option
also disables the last-resort comparison.

So to achieve your desired result (bearing in mind your first field is numeric)

$ sort -s -k1,1n file
1 c
1 b
5 f
8 a
  • Thank you,why is there last resort comparison?what is it's benefit? – Sinoosh Oct 8 '16 at 9:25
  • 2
    @Sinoosh sorry I don't know why that's the default - except that apparently the behavior is specified by the POSIX standard (likely for historical reasons - i.e. it's how the original UNIX sort was implemented). See Why is sort changing the order of lines with identical sort keys?. – steeldriver Oct 8 '16 at 11:49
3

If you want the second column to be reversed (it is not a proper answer to your specific question, but maybe it is what you are interested in), elaborating a bit from Unix StackExchange one gets:

sort -k1,1n -k2,2r file

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.