首页 > 解决方案 > 使用字母数字字符串上的一般数值进行 Bash 排序未返回正确排序的行

问题描述

我有一个包含三个 TAB 分隔列的文件。第 1 列是数字,第 2 列是 8 个字符后跟 1-3 位数字的序列,第 3 列与第 2 列相同。这是一个最小的可重现示例:

1       abceefgh10      abceefgh22
1       abceefgh10      abceefgh9
1       abceefgh11      abceefgh10
1       abceefgh13      abceefgh11
1       abceefgh14      abceefgh13
1       abceefgh15      abceefgh14
1       abceefgh17      abceefgh16
-1      abceefgh18      abceefgh17
1       abceefgh19      abceefgh18
-1      abceefgh1       abceefgh2
-1      abceefgh20      abceefgh12
1       abceefgh21      abceefgh19
1       abceefgh22      abceefgh20
-1      abceefgh23      abceefgh21
1       abceefgh24      abceefgh24
1       abceefgh2       abceefgh1
1       abceefgh3       abceefgh3
1       abceefgh5       abceefgh5
1       abceefgh6       abceefgh25
1       abceefgh6       abceefgh6
1       abceefgh7       abceefgh7
-1      abceefgh8       abceefgh3
1       abceefgh9       abceefgh8

这个示例是我尝试使用 对列进行排序时得到的sort -gk2.9

据我所知,我应该期望看到第二列从 1 到 24 排序,并且数值增加(即 1,2,3,4,... 而不是 1,10,2,20,.. .,如果使用-n)。

如果我剪切第二列并使用相同的命令 ( cut -f 2 ${file} | sort -gk1.9) 对其进行排序,我实际上得到了我想要的排序。我有什么明显的错误吗?

标签: bashshellsortingnumericalphanumeric

解决方案


使用--debug选项,您可以看到列选择没有按预期工作:

1>abceefgh10>abceefgh9  
         ^ no match for key 

根据 Nahuel 的评论指定分隔符(sort -t $'\t' --debug -gk2.9):

1>abceefgh10>abceefgh9     
          __         

推荐阅读