Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract a certain amount of lines after a pattern in perl?

Tags:

file

perl

Lets say I have a text file:

Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7 
Line 8
Line 9

So far all I have is code to find the target and print it out:

use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

like image 257
Makuza Avatar asked Dec 22 '22 19:12

Makuza


1 Answers

A basic way is to use a flag and a counter, for when to start and how much to print. One way:

use warnings;
use strict;

my $how_many = 3;

my $to_print = 0;    
while (<>) { 
    $to_print = 1+$how_many  if /Target\s+\S+/;

    print if $to_print-- > 0;
}

This uses one variable to control operation, set to the number of lines to print (plus one) whenever the "trigger" is seen and then counted down with each print. It makes some assumptions.

The <> operator reads lines from files given on the command line (or from STDIN) so run the script by passing filenames as arguments when it is invoked.

like image 177
zdim Avatar answered Dec 29 '22 11:12

zdim