Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: perl one line for advanced grep (current line and next one)

by atcroft (Monsignor)
on Sep 01, 2013 at 21:34 UTC ( #1051865=note: print w/replies, xml ) Need Help??

in reply to perl one line for advanced grep (current line and next one)

This may not be the best or most efficient way to do it, but it does appear to work (written on multiple lines for readability):


perl -ne 'if ( $flag ) { $flag++; $flag %= 3; } if ( m/error/ ) { $flag = 1; } print $., q{: }, $_ if ( $flag );' <filename>

Example output:

$ perl -ne 'if ( $flag ) { $flag++; $flag %= 3; } if (m/\$line/) { $flag = 1; }; print $., q{: }, $_ if ( $flag );' 15: while ( my $line = <$df> ) { 16: chomp $line; 17: next if ( $line =~ m/^\s*$/ ); 18: 19: if ( substr( $line, 3, 8 ) eq q{ACCOUNTA} ) { 20: print $/, $line, qq{\n}; 21: }

I started with a single if (m/.../ or $flag) statement, but in testing found that it missed the following line if the search value appeared in consecutive lines. If you want more following context, change the mod value to N+2, where N is the number of lines you want to see including the matching one (i.e., if you want 1 extra line, set to 3, 2 extra to 4, etc.).

Hope that helps.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1051865]
[1nickt]: The dangers of milk-based soup, you mean?
[Corion]: choroba: Ouch! But you don't need that many external events for that. I have on several occasions set up milk to cook and then programmed a bit, only to find the milk burned and congealed over the stove :-/
[choroba]: it's still edible, just need to scour the pot
[1nickt]: Corion I have a large site I need to check for broken links and absolute links. Making a scraper is easy of course; a spider that crawls a whole site is a little more involved ... I was planning a queue-based tool. Intersted to see what you do...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2017-10-18 11:44 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (244 votes). Check out past polls.