The code below works exactly as I want it to in my perl script. However, it takes forever to run through very large files. Would someone know a perl alternative to my grep command?
my $print = `grep --after-context=3 $line $inputfile`;
print OUTFILE $print
To explain the code above: it simply finds a line (called $line) in the input file (called $inputfile) and prints the match it found and the three lines following the match (from the $inputfile) to my outfile (called OUTFILE).
Cheers!
While there’s some overhead in launching a
grepsubprocess, it’s a fixed amount, unrelated to the size of the file. Unless you’ve got a very bad implementation ofgrep, you’re not going to be able to improve the search time in pure Perl. In fact, searching a large file using Perl is likely to be slower thangrep, which is optimized solely for searching files.If you’re only looking for the first match, you might want to add
--max-count=1to yourgrepcommand. This will causegrepto quit immediately, instead of reading the rest of the file to find additional matches.