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.
|
|---|