代码之家  ›  专栏  ›  技术社区  ›  Remi.b

`--key(-k)`如何处理命令'sort`?

  •  1
  • Remi.b  · 技术社区  · 6 年前

    从指挥手册上 sort

       -k, --key=POS1[,POS2]
              start a key at POS1, end it at POS2 (origin 1)
    

    版本:

    • 排序: GNU coreutils 5.93
    • MAC OSX 10.11.6
    • 猛击: GNU bash 3.2.57(1)
    • 2.6.1

    -k1 -k2 -k1,2 this post ), -k1.2 -k1.2n (见 this post )以及 -k3 -k1 -k4 (见 this post ).

    --key (-k) 为指挥部工作 ?


    我对这个选项能做什么只有模糊的直觉 -k 不过,如果举个例子比较方便的话,我很乐意让你考虑一下( -n )按直接跟在“行”后面的数字对下列输入进行排序。如果两个记录在单词“row”后面有相同的值,那么可以对字母“G”后面的值进行数字排序。

    H3_row24_G500.txt
    H3_row32_G1000.txt
    H3_row9_G999.txt
    H3_row9_G1000.txt
    H3_row24_G999.txt
    H3_row102_G500.txt
    H3_row2400_G999.txt
    H3_row68_G999.txt
    H3_row68_G500.txt
    

    预期输出为

    H3_row9_G999.txt
    H3_row9_G1000.txt
    H3_row24_G500.txt
    H3_row24_G999.txt
    H3_row32_G1000.txt
    H3_row68_G500.txt
    H3_row68_G999.txt
    H3_row102_G500.txt
    H3_row2400_G999.txt
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   jrwren odony    6 年前

    从手册页

       KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number
       and C a character position in the field; both are origin 1, and the stop position defaults
       to  the  line's end.  If neither -t nor -b is in effect, characters in a field are counted
       from the beginning of the preceding whitespace.  OPTS is one or more single-letter  order‐
       ing options [bdfgiMhnRrV], which override global ordering options for that key.  If no key
       is given, use the entire line as the key.  Use --debug to diagnose incorrect key usage.
    

    _ 作为分隔符,使用偏移量4。

    在本例中,字段分隔符不是空白,因此需要使用 -t 选项。

    sort -t _ -k 2.4 -n 
    
        2
  •  2
  •   chepner    6 年前

    这个 . 指定单个字段中的起始位置。您需要对字段2(从字符4开始)和字段3(从字符2开始)进行数字排序。以下应起作用:

    sort -t_ -k2.4n -k3.2n tmp.txt
    
    • -t_
    • 第一个关键是 2.4n
    • 如果第一个键相等,则第二个键为 3.2n

    从技术上讲, .txt

    (更准确地说, -k2.4,2n -k3.2,3n 防止在每个键中包含任何附加字段;我认为上面显示的更简单的形式是有效的,因为任何重叠都是“覆盖”的。 n 防止字段3本身被视为数字,并且没有字段4。)

        3
  •  1
  •   melpomene    6 年前

    如果您使用的是GNU排序,那么您所希望的输出可以通过 sort -V :

    $ echo 'H3_row24_G500.txt
    H3_row32_G1000.txt
    H3_row9_G999.txt
    H3_row9_G1000.txt
    H3_row24_G999.txt
    H3_row102_G500.txt
    H3_row2400_G999.txt
    H3_row68_G999.txt
    H3_row68_G500.txt' | sort -V
    
    H3_row9_G999.txt
    H3_row9_G1000.txt
    H3_row24_G500.txt
    H3_row24_G999.txt
    H3_row32_G1000.txt
    H3_row68_G500.txt
    H3_row68_G999.txt
    H3_row102_G500.txt
    H3_row2400_G999.txt
    

    -V compares numeric and general string segments separately H , 3 _row 在所有行中都是相同的。