I'm matching a string and want to return the next three lines after the match

会有一股神秘感。 提交于 2019-12-11 20:01:14

问题


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.



来源:https://stackoverflow.com/questions/26476583/im-matching-a-string-and-want-to-return-the-next-three-lines-after-the-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!