2

我有一个包含多组行的文本文件,因此我只需要每组的前三行。

文件:

test1|pass
test1|pass
test1|pass
test1|pass
test1|pass
test2|fail
test2|fail
test2|fail
test2|fail
test3|pass
test3|pass
test3|pass
test3|pass

预期输出:

test1|pass
test1|pass
test1|pass
test2|fail
test2|fail
test2|fail
test3|pass
test3|pass
test3|pass

到目前为止我已经尝试过:

BEGIN {
        FS = "|"
}
        $1==x {
        if (NR % 5 <= 3) {
                print $0
        }
        next
}
{
        x=$1
        print $0
}

END {
        printf "\n"
}
4

4 回答 4

5

你可以像这样相当简洁地做到这一点:

awk -F'|' '++a[$1] <= 3' infile

输出:

test1|pass
test1|pass
test1|pass
test2|fail
test2|fail
test2|fail
test3|pass
test3|pass
test3|pass

解释

a是一个关联数组。我们使用每行的第一个元素 ( $1) 作为键a并递增其值。然后将该值与该值进行比较3,如果比较为真,则执行默认块 ( {print $0})。

于 2013-02-07T11:23:26.220 回答
1
BEGIN {
        FS = "|"
}
        $1==x && count <= 3 {
        print;
        count++;
        }
        next
}
{
        x=$1;
        print;
        count=1;
}
于 2013-02-07T11:24:06.187 回答
1

使用 awk 的其他方式

awk '{a[$1]+=1}END{ for (b in a) {for(i=1; i<=3; i++) print b} }'  temp.txt | sort
于 2013-02-07T11:49:55.253 回答
0

如果您的数据像您在问题中显示的那样按升序排列,那么您可以使用此 perl 代码。

#!/usr/perl/bin -w

use strict;
use Data::Dumper;

my $file_name = "file.txt";
my $new_file = "new_file.txt";
open(FH, "<".$file) or die "Could not open $file";
open (NFH, ">$new_file") or die "Could not open $new_file";

my @content = <FH>;

my $old_line = "";
my $count = 0;
foreach my $line (@content) {

    if( ($old_line ne $line) || ($count < 3) ) {
        print NFH $line;
    }

    print NFH "$first $second $third";
}

close NFH;
close FH;

或者

如果您的数据不按顺序排列,那么您可以使用以下 Perl 代码:

#!/usr/perl/bin -w
use strict;
use Data::Dumper;

my $file_name = "file.txt";
my $new_file = "new_file.txt";
open(FH, "<".$file) or die "Could not open $file";
open (NFH, ">$new_file") or die "Could not open $new_file";

my @content = <FH>;

my %hash = map($_ => 1) @content;
my $count = 0;
foreach my $key (keys(%hash)) {
    while($count < 3) {
    print NFH $key;
    $count++;
    }
}

close NFH;
close FH;
于 2013-02-07T11:35:59.480 回答