Perl file reading and capturing specific lines

I have a text file, and I want to capture certain lines, starting from a template and ending with a specific template. Example:

Text
Text
Startpattern
print this line
Print this line
print this line
Endpattern
Text
Text
Text

A start pattern and an end pattern should also be printed. My first attempt was not really successful:


my $LOGFILE = "/var/log/logfile";
my @array;
# open the file (or die trying)

open(LOGFILE) or die("Could not open log file.");
foreach $line () {
  if($line =~  m/Sstartpattern/i){
    print $line;
    foreach $line2 () {
      if(!$line =~  m/Endpattern/i){
        print $line2;
      }
    }
  }
}
close(LOGFILE);

Thanks in advance for your help.

+3
source share
3 answers

How about this:

#!perl -w
use strict;

my $spool = 0;
my @matchingLines;

while (<DATA>) {
    if (/StartPattern/i) {
        $spool = 1;
        next;
    }
    elsif (/Endpattern/i) {
        $spool = 0;
        print map { "$_ \n" } @matchingLines;
        @matchingLines = ();
    }
    if ($spool) {
        push (@matchingLines, $_);
    }
}

__DATA__

Text
Text
Startpattern
print this line
Print this line
print this line
Endpattern
Text
Text
Text
Startpattern
print this other line
Endpattern

If you want the start and end templates to be printed as well, add push statements to this if block.

+2
source

You can use the scalar range operator :

open my $fh, "<", $file or die $!;

while (<$fh>) {
    print if /Startpattern/ .. /Endpattern/;
}
+14
source

Something like that?

my $LOGFILE = "/var/log/logfile";
open my $fh, "<$LOGFILE" or die("could not open log file: $!");
my $in = 0;

while(<$fh>)
{
    $in = 1 if /Startpattern/i;
    print if($in);
    $in = 0 if /Endpattern/i;
}
+1
source

All Articles