【问题标题】:Bash sort using general numeric value on alphanumeric string not returning rows sorted properly使用字母数字字符串上的一般数值进行 Bash 排序未返回正确排序的行
【发布时间】:2019-07-12 11:40:00
【问题描述】:

我有一个文件包含三个制表符分隔的列。第 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) 对其进行排序,我实际上得到了我想要的排序。我有什么明显的错误吗?

【问题讨论】:

  • sort -t $'\t' -V -k2 怎么样,来自this answer 一般数字排序是针对具有指数的数字
  • 谢谢,它成功了。附带说明一下,只要我使用 $'\t' 指定字段分隔符,它也可以在不使用自然版本排序 (-V) 的情况下工作。
  • 更确切地说应该是 sort -t $'\t' -V -k2,2 仅对第二列进行排序,否则也会对下一列进行排序

标签: bash shell sorting numeric alphanumeric


【解决方案1】:

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

1>abceefgh10>abceefgh9  
         ^ no match for key 

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

1>abceefgh10>abceefgh9     
          __         

【讨论】:

  • 看手册:KEYDEF ... If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace.
  • 对。删除了“糟糕的文档”段落。
猜你喜欢
  • 1970-01-01
  • 2013-06-05
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
相关资源
最近更新 更多