【问题标题】:Remove lines when three columns are identical当三列相同时删除行
【发布时间】:2012-10-18 09:02:32
【问题描述】:

我有一个制表符分隔的文件,我想删除仅在前三列中相同的行(保留一份)。我更喜欢使用 unix 来执行此操作,例如 awk 或 uniq。

输入文件:

Supercontig_1.1 241783  286397  5677    52
Supercontig_1.1 241783  286397  5678    53
Supercontig_1.1 241783  286397  5679    53
Supercontig_1.2 10500  25700  3000    57
Supercontig_1.2 10500  25700  3001    59
Supercontig_1.2 10500  25700  3002    59
Supercontig_1.3 2000  7000  5686    60
Supercontig_1.3 2000  7000  5687    60

输出:

 Supercontig_1.1 241783  286397  5677    52
 Supercontig_1.2 10500  25700  3000    57
 Supercontig_1.3 2000  7000  5686    60

【问题讨论】:

    标签: unix awk uniq


    【解决方案1】:

    一种使用awk的方式:

    awk '!array[$1,$2,$3]++' file.txt
    

    结果:

    Supercontig_1.1 241783 286397 5677 52
    Supercontig_1.2 10500 25700 3000 57
    Supercontig_1.3 2000 7000 5686 60
    

    【讨论】:

    • 小心 - 例如,如果第一行包含“1 23 4”而第二行包含“1 2 34”,那么连接这样的字段将产生错误的输出,因为它们都将映射到“1234”。为此,您需要使用伪多维数组:!a[$1,$2,$3]++。
    • 感谢@EdMorton! - 小的疏忽。我想我经常使用FS,但即使这样可能也有问题。我做了一些测试,逗号实际上设置了空分隔符:\0。很有趣。
    • 逗号被转换为 SUBSEP 内置变量的值。这就是为什么我说“伪”-多维,因为它不是真正的多维,你只得到一个由 $1 SUBSEP $2 SUBSEP $3 组成的索引。让您可以执行“for (idx in array) { split(idx,idxA,SUBSEP);...}”以在 idxA 数组中返回 $1、$2 和 $3。
    • @EdMorton:哇,我还在学习awk。之前没碰过SUBSEP。我通常使用FS。很酷的提示,谢谢!
    【解决方案2】:

    这个 oneliner 可以解决问题:

    awk '!a[$1$2$3]++' file
    

    测试

    kent$  echo "Supercontig_1.1 241783  286397  5677    52
    dquote> Supercontig_1.1 241783  286397  5678    53
    dquote> Supercontig_1.1 241783  286397  5679    53
    dquote> Supercontig_1.2 10500  25700  3000    57
    dquote> Supercontig_1.2 10500  25700  3001    59
    dquote> Supercontig_1.2 10500  25700  3002    59
    dquote> Supercontig_1.3 2000  7000  5686    60
    dquote> Supercontig_1.3 2000  7000  5687    60
    dquote> "|awk '!a[$1$2$3]++'
    Supercontig_1.1 241783  286397  5677    52
    Supercontig_1.2 10500  25700  3000    57
    Supercontig_1.3 2000  7000  5686    60
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      相关资源
      最近更新 更多