linux - 使用 Linux 排序命令对多个键进行排序

标签 linux shell unix sorting

假设我有这个文件。

$ 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/

相关文章:

c - 检查 C 代码是否已弃用 POSIX 调用的最佳方法是什么?

php - 查找字符串超过 50 个字符的 php 文件

linux - OpenSSL 错误和 linux 进程内存管理

c++ - 如何在 Linux 中从 Cirque 触摸板读取点击的绝对位置

linux - 将命令输出存储到变量时如何保留换行符?

linux - 我怎样才能在bash shell脚本中编写这种for循环?

php - 使用反引号(重音符)时字符串操作的规则是什么?

linux - 如何将文件的行分成其他文件

c - 来自 proc_fs.h 的 proc_create_entry 错误 "implicit declaration"

linux - 如何在 bash 中使用 tr 删除行首的所有空格