使用perl添加第三列,直到第二列的特定行

  • 本文关键字:二列 三列 添加 perl 使用 perl
  • 更新时间 :
  • 英文 :


我的输入如下:

atom 1 23
atom 1 13
atom 1 22
atom 1 24
atom 2 99
atom 2 98
atom 2 21
atom 3 15
atom 3 20
atom 4 19
atom 5 11

我想合计第三列,但它应该像在第二列中读取1一样报告,它应该给出第三列中所有1的值的总和。类似地,如果第二列中的值为2,则第三列中的总值应为2。类似地,在第二列中,如果它是三,那么它应该在第三列中给出三的总和。同样,直到文件结束。请帮我解决这个问题。。

也许以下内容会有所帮助:

use strict;
use warnings;
my %hash;
while (<>) {
    my @elems = split;
    $hash{ $elems[1] } += $elems[2];
}
print "atom $_ $hash{$_}n" for sort { $a <=> $b } keys %hash;

用法:perl script.pl inFile [>outFile]

最后一个可选参数将输出导向一个文件。

数据集上的输出:

atom 1 82
atom 2 218
atom 3 35
atom 4 19
atom 5 11

最新更新