【问题标题】:Confused about GNU `sort(1)` of a numerical sub field对数字子字段的 GNU `sort(1)` 感到困惑
【发布时间】:2010-05-30 09:03:36
【问题描述】:

我希望使用在第二个字段中找到的数值对一个空格分隔的table 进行排序。我可以假设第二个字段总是 fooN 但 N 的长度是未知的:

antiq. foo11 girls
colleaguing foo2 Leinsdorf
Cousy foo0 Montgomeryville
bowlegged foo1 pollack
Chevrier foo10 ill-conceived
candlebomb foo3 seventieths
autochthony foo101 re-enable
beneficiate foo100 osteometric

我阅读了man sort(1) 并尝试了各种选项。在我的系统上,我找到了这条线:

sort -n -k2.5 table

上班。

我的问题是为什么?

根据手册页:

-k, --key=POS1[,POS2]
   start a key at POS1, end it at POS 2 (origin 1) 
...
POS is F[.C][OPTS], where F is the field number and C the characterposition in the
field. OPTS is one or more single-letter ordering options, which override global
ordering options for that key. If no key is given, use the entire line as the key. 

那么为什么sort -n -k2.4 表不起作用而sort -n -k2.5 起作用?

【问题讨论】:

  • sort -n -k.5 是指sort -n -k2.5
  • @dalle,是的,你是对的。固定。

标签: sorting command-line command gnu gnu-sort


【解决方案1】:

我不知道它是否有帮助,但 info sort 声明如下:

排序 -t : -k 2,2n -k 5.3,5.4

 Note that if you had written `-k 2' instead of `-k 2,2' `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.

也许尝试在-k2 之间添加一个空格,或者尝试设置POS2

【讨论】:

    【解决方案2】:

    答案是:前导空格算作字段的一部分,除非:

    sort -b -n -k2.4 table
    

    或者好奇:

    LC_ALL=C sort -t" " -n -k2.4 table
    

    这也会产生正确的结果。


    ...还有一件事...

    好像用起来比较好:

    sort -b -n -k2.4,2 table
    

    因此将排序限制在第二个字段的末尾。

    【讨论】:

    • 伟大的发现。让我补充一下:或者,如果您将[-]n 选项直接添加到字段索引(如果您有多个具有不同排序逻辑的键,则需要),您还必须将[-]b 选项放在那里;因此,相当于您的第一个命令是:sort -k2.4bn,2 table.
    • 第二条命令:我认为 'LC_ALL=C' 部分是不必要的。该命令有效(假设每个字段之间有 1 个空格),因为 sort - 与默认情况不同 - 不会在指定 -t 时考虑字段的前面分隔符部分(即使参数是一个空格)。然而,还有另一个更细微的区别:默认情况下,多个相邻的空白被视为一个分隔符;使用-t,它们不是 - 多个相邻的视为空字段,必须相应调整字段索引。
    • 第 3 条命令:很重要 - 出乎意料的默认设置是在密钥中包含 整行 的其余部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2012-01-04
    • 2015-03-13
    相关资源
    最近更新 更多