in reply to How do I search this binary file?
All you need to do is a little buffering like:
my $last4 = ''; my $buffer = ''; my $find = qr /1234/; my $chunk = 7; # 2**20 or some such is more logical! while ( read ( DATA, $buffer, $chunk ) ) { print "got last-$last4\tbuffer-$buffer\n"; print "simple match\n" while $buffer =~ s/$find//; $buffer = $last4 . $buffer; $last4 = substr $buffer, -4, 4, ''; print "buffer match\n" if $buffer =~ m/$find/; } __DATA__ 1234567890123456789012345678901234567890123456789012345678901234567890 __END__ got last- buffer-1234567 simple match got last-567 buffer-8901234 simple match got last-7890 buffer-5678901 got last-8901 buffer-2345678 buffer match got last-5678 buffer-9012345 simple match got last-8905 buffer-6789012 got last-9012 buffer-3456789 buffer match got last-6789 buffer-0123456 simple match got last-9056 buffer-7890123 got last-0123 buffer-4567890 buffer match got last-7890 buffer-
In this example I use a chunk size of 7 so that we need the buffer often but 2**20 (megabyte) chunks work effectively with big files (I wrote a node about processing big files fast at Re: Performance Question). You should be able to get around a 4-8MB/s throughput depending on your hardware.
I'll leave it as an exercise for you as to what to do with the data between matches. Logging the positions and making a second pass through the file to get the data may well be most efficient.
Note if we match out of the initial buffer we s/// it out before we add the previously buffered chunk and retest (avoids double match) - replace with a filler string to maintain length. There are 7 matches available and 7 found. A dozen lines with debugging - you gotta love Perl.
Here is a version that records the positions of matches for you
my $last4 = ''; my $buffer = ''; my $find = '1234'; my $find_re = qr /$find/; my $length = length $find; my $chunk = 7; # 2**20 or some such is more logical! my $pos = 0; while ( my $read_length = read ( DATA, $buffer, $chunk ) ) { $buffer = $last4 . $buffer; print "got last-$last4\tbuffer-$buffer\n"; while ($buffer =~ m/$find_re/g) { print "match at ", $pos - (length $last4) -$length + pos $bu +ffer, "\n"; } $last4 = substr $buffer, -$length, $length, ''; $last4 = '' if $last4 =~ m/$find_re/; # stop double match bug $pos += $read_length; } __DATA__ 1234567890123456789012345678901234567890123456789012345678901234567890
cheers
tachyon
s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How do I search this binary file?
by Aristotle (Chancellor) on Aug 21, 2002 at 01:47 UTC | |
|
Re: Re: How do I search this binary file?
by John M. Dlugosz (Monsignor) on Aug 20, 2002 at 22:23 UTC | |
by tachyon (Chancellor) on Aug 20, 2002 at 22:42 UTC |