republican-creole
site Search:


 
    All Forums Hot Topics Gallery






how-to block ads


 
Search Topic:
Uniqs:
602
Share Topic
Posting?
Post a:
Post a:
Links: ·Forum FAQ ·Attitude Adjustment ·Linux docs ·DistroWatch ·OPLM
AuthorAll Replies


Chewbakka

join:2004-12-19

return lines after regex match perl

Hi,

I'm parsing log files in a perl script and need to somehow return the lines after a specific regex match, similar to grep -A. What is the right way to do this?

dave
Premium,MVM
join:2000-05-04
not in ohio
kudos:8

Simply do it.

while read; not at end of file {
    next if doesn't match regexp;
    output the matched line;
    for up to N and while not at end of file {
          read the line;
          output the line;
    }
}
 

Note, ignores the case where the regexp occurs again within the N lines; you have to decide what you want to happen there.


pflog
Bueller? Bueller?
Premium,MVM
join:2001-09-01
El Dorado Hills, CA
kudos:3

reply to Chewbakka
Just grab the next line from your file handle after the match:

perl code:

my $data = undef;
while(my $line = <$fh>) {
chomp($line);

if($line =~ /$re/) {
chomp($data = <$fh>);
last;
}
}

if(! $data) {
print "Data not found.\n";
} else {
print "Found data line: $data\n";
}

Something to that effect. And like dave See Profile says, you'll want to handle corner cases (e.g. what do you do when you have a match on back-to-back lines, etc).

--
"Women. Can't live with 'em, pass the beer nuts." -Norm

Wednesday, 19-Jun 13:52:25 Terms of Use & Privacy | feedback | contact | Hosting by nac.net - DSL,Hosting & Co-lo
over 13.5 years online © 1999-2013 dslreports.com.
Most commented news this week
Hot Topics