【问题标题】:sed - Delete lines only if they contain multiple instances of a stringsed - 仅当它们包含多个字符串实例时才删除行
【发布时间】:2019-08-09 06:14:58
【问题描述】:

我有一个文本文件,其中包含许多具有部分重复字符串的行。我想删除字符串匹配出现两次的行,这样我只剩下一个匹配的行(或根本不匹配)。

示例输出:

g1: sample1_out|g2039.t1.faa sample1_out|g334.t1.faa sample1_out|g5678.t1.faa sample2_out|g361.t1.faa sample3_out|g1380.t1.faa sample4_out|g597.t1.faa
g2: sample1_out|g2134.t1.faa sample2_out|g1940.t1.faa sample2_out|g45.t1.faa sample4_out|g1246.t1.faa sample3_out|g2594.t1.faa
g3: sample1_out|g2198.t1.faa sample5_out|g1035.t1.faa sample3_out|g1504.t1.faa sample5_out|g441.t1.faa
g4: sample1_out|g2357.t1.faa sample2_out|g686.t1.faa sample3_out|g1251.t1.faa sample4_out|g2021.t1.faa

在这种情况下,我想删除第 1、2 和 3 行,因为 sample1 在第 1 行重复多次,sample 2 在第 2 行重复两次,sample 5 在第 3 行重复两次。第 4 行将通过因为它只包含每个样本的一个实例。

我可以使用不同的“匹配”字符串多次重复此操作(例如上例中的 sample1_out、sample2_out 等)。

【问题讨论】:

    标签: string awk sed duplicates


    【解决方案1】:

    这是 GNU awk 中的一个:

    $ awk -F"[| ]" '{         # pipe or space is the field reparator
        delete a              # delete previous hash
        for(i=2;i<=NF;i+=2)   # iterate every other field, ie right side of space
            if($i in a)       # if it has been seen already
                next          # skit this record
            else              # well, else
                a[$i]         # hash this entry
        print                 # output if you make it this far
    }' file
    

    输出:

    g4: sample1_out|g2357.t1.faa sample2_out|g686.t1.faa sample3_out|g1251.t1.faa sample4_out|g2021.t1.faa
    

    【讨论】:

      【解决方案2】:

      下面的sed 命令将完成你想要的。

      sed -ne '/.* \(.*\)|.*\1.*/!p' file.txt
      

      【讨论】:

        【解决方案3】:

        grep:grep -vE '(sample[0-9]).*\1' file

        【讨论】:

          【解决方案4】:

          从 Glenn 的回答中得到启发:使用 -i 和 sed 直接对文件进行更改。

          sed -r '/(sample[0-9]).*\1/d' txt_file
          

          【讨论】:

            猜你喜欢
            • 2013-02-16
            • 2013-08-21
            • 2022-12-17
            • 2011-10-13
            • 1970-01-01
            • 2012-03-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多