Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

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

by atcroft (Abbot)
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]
LanX imagines which nations would be dominating if the winter olympics were invented in East Asia
[LanX]: Corion: and that's the clue how Germany can dominate Handball tournaments, just continuing the domestic league and forbidding the best players of the world to attend :)
LanX (which would be a good scheme for England and football too)
[LanX]: If "Canada will play the Czech Republic for bronze on Saturday", that means Germany will play Syria in disguise...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (11)
As of 2018-02-23 16:42 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (303 votes). Check out past polls.