按列分组并打印一个值

时间:2013-02-25 16:41:30

标签: perl perl-data-structures

我有一个如下所示的文件:

LINE abc 1 somevalue
LINE abc 1 somevalue
LINE abc 1 somevalue
LINE def 2 somevalue
LINE def 2 somevalue
LINE abc 3 somevalue
LINE abc 3 somevalue
LINE mno 4 somevalue
LINE mno 4 somevalue
LINE def 5 somevalue
LINE def 5 somevalue

我想打印一次'abc'或'def'(可以由第3列标识)等,因为它存在于多行中。我希望得出结论:

LINE abc 1 somevalue
LINE abc 1 somevalue
LINE abc 1 somevalue
LINE def 2 somevalue
LINE def 2 somevalue
LINE mno 4 somevalue
LINE mno 4 somevalue

任何人都能帮助我进入perl吗?

2 个答案:

答案 0 :(得分:2)

您可以将已经看到的行保存在哈希中并跳过已识别的行

use strict;
use warnings;

my %seen;

while (<>) {
    my @cols = split;
    if (defined($seen{$cols[1]})) {
        if ($seen{$cols[1]} == $cols[2]) {
            print;
        }
    } else {
        $seen{$cols[1]} = $cols[2];
        print;
    }
}

如果第二列已出现在%seen哈希中,则会读取行并查看。如果是,则打印该行,如果第三列相同。否则,它会将该行存储为新行,以供日后参考。

答案 1 :(得分:1)

我必须说,你显示的输出与我能提出的问题陈述的任何合理解释都不匹配“我想打印一次'abc'或'def'(可以由第3列

标识
#!/usr/bin/env perl

while (my $line = <DATA>) {
    my @cols = split ' ', $line;
    next if ($cols[1] =~ /\A(?:abc|def)\z/) # if col 2 is abc or def
        and $cols[2] != 1;                  # and col 3 is not 1, then skip
    print $line;                            # otherwise print
}

__DATA__
LINE abc 1 somevalue
LINE abc 1 somevalue
LINE abc 1 somevalue
LINE def 2 somevalue
LINE def 2 somevalue
LINE abc 3 somevalue
LINE abc 3 somevalue
LINE mno 4 somevalue
LINE mno 4 somevalue
LINE def 5 somevalue
LINE def 5 somevalue

或者,如果你想在命令行上使用它,

$ perl -ane '$F[1] =~ /\A(?:abc|def)\z/ and $F[2] != 1 and next or print' input

相关问题