Why are the outputs of `sort`, `sort k 1`, `sort k 1,1` equal?
Matthew Barrera
I have a file:
$ cat file
1 c
8 a
1 b
5 fI 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 aI 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 aWhy 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 aIf it is not correct please tell me what is my mistake and how can I get output like that?
2 Answers
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 2 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