【问题标题】:Output whole line once for each unique value of a column (Bash)为列的每个唯一值输出一次整行(Bash)
【发布时间】:2012-08-21 10:09:45
【问题描述】:

对于awk 或其他方式,这肯定是一项微不足道的任务,但今天早上让我摸不着头脑。我有一个格式类似于此的文件:

pep> AEYTCVAETK     2   genes ADUm.1024,ADUm.5198,ADUm.750
pep> AIQLTGK        1   genes ADUm.1999,ADUm.3560
pep> AIQLTGK        8   genes ADUm.1999,ADUm.3560
pep> KHEPPTEVDIEGR  5   genes ADUm.367
pep> VSSILEDKTT     9   genes ADUm.1192,ADUm.2731
pep> AIQLTGK        10  genes ADUm.1999,ADUm.3560
pep> VSSILEDKILSR   3   genes ADUm.2146,ADUm.5750
pep> VSSILEDKILSR   2   genes ADUm.2146,ADUm.5750

我想为第 2 列中肽段的每个不同值打印一行,这意味着上述输入将变为:

pep> AEYTCVAETK     2   genes ADUm.1024,ADUm.5198,ADUm.750
pep> AIQLTGK        1   genes ADUm.1999,ADUm.3560
pep> KHEPPTEVDIEGR  5   genes ADUm.367
pep> VSSILEDKTT     9   genes ADUm.1192,ADUm.2731
pep> VSSILEDKILSR   3   genes ADUm.2146,ADUm.5750

这是我迄今为止尝试过的,但显然我不需要:

awk '{print $2}' file | sort | uniq
# Prints only the peptides...
awk '{print $0, "\t", $1}' file |sort | uniq -u -f 4
# Altogether omits peptides which are not unique...

最后一件事,它需要将作为其他肽段子串的肽段视为不同的值(例如 VSSILED 和 VSSILEDKILSR)。谢谢:)

【问题讨论】:

    标签: bash shell awk uniq


    【解决方案1】:

    只需使用排序:

    sort -k 2,2 -u file
    

    -u 删除重复条目(如您所愿),-k 2,2 仅使字段 2 成为排序字段(因此在检查重复项时忽略其余部分)。

    【讨论】:

    【解决方案2】:

    一种使用awk的方式:

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

    结果:

    pep> AEYTCVAETK     2   genes ADUm.1024,ADUm.5198,ADUm.750
    pep> AIQLTGK        1   genes ADUm.1999,ADUm.3560
    pep> KHEPPTEVDIEGR  5   genes ADUm.367
    pep> VSSILEDKTT     9   genes ADUm.1192,ADUm.2731
    pep> VSSILEDKILSR   3   genes ADUm.2146,ADUm.5750
    

    【讨论】:

      【解决方案3】:

      我会为此使用 Perl:

      perl -nae 'print unless exists $seen{$F[1]}; undef $seen{$F[1]}' < input.txt
      

      n 开关与输入逐行工作,a 开关将行拆分为@F 数组。

      【讨论】:

      • awk 中的相同内容:awk '{ if(!($2 in peptides)) { peptides[$2] = 1;打印 $_ } } ' > fp
      • 我可以看到这是 Perl 真正擅长的地方。很好的答案,谢谢。
      【解决方案4】:
      awk '{if($2==temp){next;}else{print}temp=$2}' your_file
      

      测试如下:

      > awk '{if($2==temp){next;}else{print}temp=$2}' temp
      pep> AEYTCVAETK         2       genes ADUm.1024,ADUm.5198,ADUm.750
      pep> AIQLTGK            1       genes ADUm.1999,ADUm.3560
      pep> KHEPPTEVDIEGR      5       genes ADUm.367
      pep> VSSILEDKTT         9       genes ADUm.1192,ADUm.2731
      pep> AIQLTGK            10      genes ADUm.1999,ADUm.3560
      pep> VSSILEDKILSR       3       genes ADUm.2146,ADUm.5750
      

      【讨论】:

      • 更详细但很容易理解。谢谢:)
      • 这会返回两次AIQLTGK
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 2012-08-17
      • 2011-05-12
      • 1970-01-01
      • 2015-09-03
      • 2021-08-09
      相关资源
      最近更新 更多