Not addressing the "save previous lines" issue, but to help you with Perl searching in general.
There are alot of Perl file greppers around, like
vfgrep and
peg - Perl _expression_ (GNU) grep script and
Gtk2 Visual Grep
I use this all the time for searching. There are alot of things to consider, like just searching the filenames itself, skipping binary files, recursion, using a regex pattern instead of literal words, precompiling your regex for efficiency,etc.
#!/usr/bin/perl
use warnings;
use strict;
use File::Find;
$|++;
# defaults are case-insensitive, no recurse, open and search files (no
+t filename)
if ($#ARGV < 0){die "Usage zgrep 'pattern' c(case sensitive optional)
+r(recurse optional) n(search name only optional)
examples: zgrep 'debug me' r
will recursively search all files for 'debug me'\n";
}
my ($recurse, $name, $case) =(0,0,0);
if( grep{/\bn\b/} @ARGV ){@ARGV = grep { $_ ne 'n' } @ARGV; $name = 1
+};
if( grep{/\br\b/} @ARGV ){@ARGV = grep { $_ ne 'r' } @ARGV; $recurse =
+ 1 };
if( grep{/\bc\b/} @ARGV ){@ARGV = grep { $_ ne 'c' } @ARGV; $case = 1
+};
#print "$name $recurse $case @ARGV\n";
my $path = '.';
#only accept 1 search string, so quote phrases
my $search = $ARGV[0];
my $regex; #defaults to case insensitive
if ($case){$regex = qr/\Q$search\E/}
else{$regex = qr/\Q$search\E/i}
# use s modifier for multiline match
find (sub {
#skip directories which begin with 1
if (-d && $_ =~ /^1.*$/) {
$File::Find::prune = 1;
return;
}
if( ! $recurse ){
my $n = ($File::Find::name) =~ tr!/!!; #count slashes in file
return $File::Find::prune = 1 if ($n > 1);
}
return if -d;
return unless (-f and -T ); # don't waste time on binaries
if($name){
if ($_ =~ /$regex/){print "$File::Find::name\n"};
}else{
open (FH,"< $_");
while(<FH>){
print "$File::Find::name: $. :$_\n " if /$regex/;
}
close FH;
}
}, $path);
exit;
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.