Skip to content

Instantly share code, notes, and snippets.

@mshock
Created May 15, 2012 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mshock/2702555 to your computer and use it in GitHub Desktop.
Save mshock/2702555 to your computer and use it in GitHub Desktop.
regex grep
#!/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
@mshock
Copy link
Author

mshock commented May 15, 2012

A quick regex which emulates the grep-like functionality of finding a lines and getting previous and following lines.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment