【问题标题】:Print lines that contain a value in a specific column shared by more than 1 entity in another col打印包含由另一个列中的多个实体共享的特定列中的值的行
【发布时间】:2013-10-31 11:58:11
【问题描述】:

我只想提取第 2 列中由第 2 列中至少 2 个唯一值共享的值。

使用相同的输入(在本例中为 3 个制表符分隔的列):

waterline-n    below-sheath-v    14.8097 
dock-n    below-sheath-v     14.5095 
waterline-n    below-steel-n    11.0330 
picnic-n    below-steel-n    12.2277 
wavefront-n    at-part-of-variance-n    18.4888 
wavefront-n    between-part-of-variance-n    17.0656
audience-b    between-part-of-variance-n    17.6346 
game-n    between-part-of-variance-n    14.9652 
whereabouts-n    become-rediscovery-n    11.3556 
whereabouts-n    get-tee-n    10.9091

对于以下所需的输出:

waterline-n    below-sheath-v    14.8097 
dock-n    below-sheath-v     14.5095 
waterline-n    below-steel-n    11.0330
picnic-n    below-steel-n    12.2277 
wavefront-n    between-part-of-variance-n    17.0656 
audience-b    between-part-of-variance-n    17.6346 
game-n    between-part-of-variance-n    14.9652

是否可以使用 grep 来做到这一点?

【问题讨论】:

    标签: terminal grep


    【解决方案1】:

    使用awk 读取文件两次并使用数组。
    我认为仅使用grep 很难做到这一点。

    awk 'FNR==NR {a[$2]++;next} a[$2]>1' file file
    waterline-n    below-sheath-v    14.8097
    dock-n    below-sheath-v     14.5095
    waterline-n    below-steel-n    11.0330
    picnic-n    below-steel-n    12.2277
    wavefront-n    between-part-of-variance-n    17.0656
    audience-b    between-part-of-variance-n    17.6346
    game-n    between-part-of-variance-n    14.9652
    

    在第一次传递FNR==NR 中,它将第 2 列的所有值添加到一个数组中,并为每次通过的命中增加它。
    在 pass 2 中,它在数组中查找,看看 hits 是否超过一个,如果没问题,打印该行。

    【讨论】:

      【解决方案2】:

      您可以使用grepuniq 获得所需的输出。请注意,第二列与其他列之间不应有对应关系。另请注意,除非您对cut 的输出进行排序,否则相同的字段需要位于连续的行上:

      grep -f <(cut -f2 infile | uniq -d) infile
      

      输出:

      waterline-n below-sheath-v  14.8097
      dock-n  below-sheath-v  14.5095
      waterline-n below-steel-n   11.0330
      picnic-n    below-steel-n   12.2277
      wavefront-n between-part-of-variance-n  17.0656
      audience-b  between-part-of-variance-n  17.6346
      game-n  between-part-of-variance-n  14.9652
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        相关资源
        最近更新 更多