为什么 `sort`、`sort k 1`、`sort k 1,1` 的输出相等?

为什么 `sort`、`sort k 1`、`sort k 1,1` 的输出相等?

我有一个文件:

$ cat file
1 c
8 a
1 b
5 f

我认为sort开头的命令会比较所有行的第一个字段并对它们进行排序,然后对具有相等第一个字段的行进行排序,并再次开始对第二个字段进行排序,如下所示:

$sort file
1 b
1 c
5 f
8 a

我读到了有关选项k 1和之间的区别k 1,1:使用k 1它,排序键可能会延续到行尾,但是使用k 1,1它应该只对第一个字段进行排序而不考虑其他字段,但是:

$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

sort为什么= sort k 1=的输出sort k 1,1相等?

我认为输出sort k 1,1 file应该是

1 c 
1 b
5 f
8 a

如果不正确,请告诉我我的错误是什么以及如何获得这样的输出?

答案1

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.

因此为了达到你想要的结果(记住你的第一个字段是数字)

$ sort -s -k1,1n file
1 c
1 b
5 f
8 a

答案2

如果你想让第二列反转(这不是你具体问题的正确答案,但也许是你感兴趣的),从Unix StackExchange得到:

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

相关内容