Created
May 15, 2012 15:15
-
-
Save mshock/2702555 to your computer and use it in GitHub Desktop.
regex grep
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
$/ = undef; | |
$file = <DATA>; | |
$/ = "\n"; | |
$lines_up = 2; | |
$lines_down = 1; | |
$pattern = 'bbb'; | |
@matches = $file =~ /((?:.*\n?){$lines_up}) | |
(.*$pattern.*\n?) | |
((?:.*\n?){$lines_down})/gx; | |
$run = 0; | |
@vals = qw(lines_up pattern lines_down); | |
for (@matches) { | |
if (! ($index = $run++ % 3)) { | |
print "match #" . (int($run / 3) + 1) . " in file\n"; | |
} | |
print $vals[$index] . ":\n$_\n"; | |
} | |
#print "1:$1\n2:$2\n3:$3"; | |
__DATA__ | |
#begin | |
aaa | |
bbb | |
ccc | |
ddd | |
#end | |
#begin2 | |
xxx | |
ccc | |
bbb | |
#end2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A quick regex which emulates the grep-like functionality of finding a lines and getting previous and following lines.