grep(1) -v -f (fgrep -v) does not do what one would hope,
and so I whipped up the following:
UPDATE:
- FIXED
DOH, -P returns the whole FILE
- FIXED
DOH, -P returns more matches (false negatives) than vfgrep without -P (stupid cut & paste error)
- *SIGH* The non-functioning of -v -f is not intended and appears to be a bug that shows up under some circumstances (in this case cygwin with grep 2.5.10 and some large CSVs). Even where the native grep does work this implementation may be faster (plain is about 6x and -P 18x than GNU fgrep -v here)
use Getopt::Std;
use vars qw'$opt_f $opt_P $VERSION';
$VERSION = 0.08;
unless( @ARGV ){
print<<EOUsage;
usage: vfgrep [-P] -f PATTERNS [FILE]
-P prune patterns on match, if a pattern will only match once per file
this can speed up execution by discarding the pattern once it has m
+atched.
EOUsage
exit;
}
getopts('Pf:');
die("vfgrep requires a pattern file\n") unless defined $opt_f;
open(PAT, $opt_f) or die("Error opening pattern file '$opt_f': $!\n");
#Strip any sort of EOL garbage
#Also pre-compile the regexp for a major performance boost
my @PAT = map{ y/\r\n//d; qr/$_/ } <PAT>;
close(PAT);
if( $opt_P ){
REC: while(<>){
#Premature optimization?
last unless scalar @PAT;
foreach my $i (0 .. $#PAT ){
splice(@PAT, $i, 1) && next REC if /$PAT[$i]/;
}
print;
}
print <> unless eof; #Pairs with last unless
}
else{
REC: while(<>){
foreach my $pattern ( @PAT ){
next REC if /$pattern/;
}
print;
}
}
__END__
Todo: mmap?
Thanks to
tye,
Corion and
diotalevi for algorithm
assistance in pruning a list currently being iterated over.
Note: In my tests case (what I wrote this for) pruning
cut the run time by 2/3.
--
In Bob We Trust, All Others Bring Data.
In reply to vfgrep
by belg4mit
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.