Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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):

Code:

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 );' test.pl 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.


Comment on Re: perl one line for advanced grep (current line and next one)
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1051865]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (9)
As of 2014-10-01 15:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (29 votes), past polls