我有一个文件:
$ cat file
1 c
8 a
1 b
5 f
Run Code Online (Sandbox Code Playgroud)
我认为sort开头的命令比较所有行的第一个字段并对它们进行排序,然后对于这些行具有相同的第一个字段,然后再次开始对第二个字段进行排序,如下所示:
$sort file
1 b
1 c
5 f
8 a
Run Code Online (Sandbox Code Playgroud)
我读到了选项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
Run Code Online (Sandbox Code Playgroud)
为什么的输出sort= sort k 1=sort k 1,1等于?
我认为输出sort k 1,1 file应该是
1 c
1 b
5 f
8 a
Run Code Online (Sandbox Code Playgroud)
如果不正确,请告诉我我的错误是什么,我怎样才能得到这样的输出?
从 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.Run Code Online (Sandbox Code Playgroud)
所以为了达到你想要的结果(记住你的第一个字段是数字)
$ sort -s -k1,1n file
1 c
1 b
5 f
8 a
Run Code Online (Sandbox Code Playgroud)