I'm matching a string and want to return the n

2019-09-06 18:52发布

问题:

I'm matching a string and want to return the next three lines after the match. I know that $_ will return the line but I'm not sure what expression to use to return the next two lines in the file that I have. Here the code I have:

open my $fh, '>', "${file}result.txt" or die $!;
       $fh->print("$file\t$_\n");
       print "$_\n";

Thanks in advance for the help and not making too much fun.

回答1:

Keeping it simple:

while (<$infile>)
{
    if (/REGEX/)
    {
        $outfile->print($_);
        $outfile->print($infile->getline) for 0 .. 1;
    }
}

The IO::Handle methods are nice for a couple of reasons. $infile->getline is like <>, but only ever grabs one line (whereas <> will return all lines in list context). It also doesn't clobber $_ or warn at the end of the file (although sometimes the latter behavior is desirable).



回答2:

#!/usr/bin/perl

open (FH, "input.txt") or die $!;

my @contents = <FH>;
my $count = 0;

map
{
   $count ++;
   if($_ =~ /This/)
   {
       print "\nNext 3 lines:\n$contents[$count+1] $contents[$count+2] $contents[$count+3]";
   }
} @contents;

This Will do it.

Thanks.