JohnDoe
JohnDoe

Reputation: 163

perl reading file and grabbing specific lines

I have a text file and I want to grab specific lines starting with a pattern and ending with a specific pattern. Example:

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

Also the start pattern and the end pattern should be printed. My first try 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.

Upvotes: 3

Views: 14783

Answers (3)

Bee
Bee

Reputation: 958

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 patterns to also be printed, add the push statements in that if block as well.

Upvotes: 2

jho
jho

Reputation: 2253

Something like this?

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;
}

Upvotes: 1

Eugene Yarmash
Eugene Yarmash

Reputation: 149796

You can use the scalar range operator:

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

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

Upvotes: 14

Related Questions