假设我有这个文件。
$ cat a.txt
c 1002 4
f 1001 1
d 1003 1
a 1001 3
e 1004 2
b 1001 2
我想按第二列排序,然后按第三列排序。第二列是数字,而第三列可以被视为字符串。我知道以下命令运行良好。
$ sort -k2,2n -k3,3 a.txt
f 1001 1
b 1001 2
a 1001 3
c 1002 4
d 1003 1
e 1004 2
但是,我认为 sort -k2n a.txt
应该也可以工作,但实际上没有。
$ sort -k2n a.txt
a 1001 3
b 1001 2
f 1001 1
c 1002 4
d 1003 1
e 1004 2
它似乎按第二列排序,然后按第一列而不是第三列排序。为什么会这样?是不是错误?因为 sort -k2 a.txt
可以正常处理上述数据,因为这些数字只是固定宽度。
我的排序版本是 cygwin 中的 sort (GNU coreutils) 8.15
。
最佳答案
我在 GNU sort docs 中找到了这条警告.
Sort numerically on the second field and resolve ties by sorting alphabetically on the third and fourth characters of field five. Use ‘:’ as the field delimiter.
sort -t : -k 2,2n -k 5.3,5.4
Note that if you had written -k 2n instead of -k 2,2n sort would have used all characters beginning in the second field and extending to the end of the line as the primary numeric key. For the large majority of applications, treating keys spanning more than one field as numeric will not do what you expect.
我不确定当它将“1001 3”计算为数字键时它最终会得到什么,但“不会做你期望的事情”是准确的。似乎很清楚,正确的做法是独立指定每个键。
同一个网页说的是解决“关系”。
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.
我承认我对如何解释它有点迷惑。
关于linux - 使用 Linux 排序命令对多个键进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16998627/