Please create an account to participate in the Slashdot moderation system

 



Forgot your password?
typodupeerror
×
Perl

Journal joke_dst's Journal: Perl script for finding patterns

Ok, I reallt needed a bash command that could list the index of every occurance of a pattern in a file. I found this one-liner before:

perl -0777 -ne 'print index $_, "\x5d\x00\x00\x80\x00\x00"' afile.bin

This locates the first LZMA header in a file, but I need to find ALL headers, not just the first... Ok, I'm no perl specialist, but I came up with this:

#!/usr/bin/perl
use strict;
use warnings;

my $count = @ARGV;
if ( $count < 2 ) {
print "bff - Binary Find in Files. Finds all occurances of a string in a file\nusage: bff <string> <filename>\n";
exit();
}

open FILE, $ARGV[1] or die $!;
my $char = eval '"'.$ARGV[0].'"';
my $offset = 0;
my $result = index(<FILE>, $char);

while ($result != -1) {
$offset += $result;
print "Found at $offset\n";

$offset += 1;
seek FILE, $offset, 0;
$result = index(<FILE>, $char);
}

This allows me to write

bff "\x5d\x00\x00\x80\x00\x00" afile.bin

and lists all occurances of the header in the file.

As always, this is a personal reference page, but use it if you like it...

This discussion has been archived. No new comments can be posted.

Perl script for finding patterns

Comments Filter:

And it should be the law: If you use the word `paradigm' without knowing what the dictionary says it means, you go to jail. No exceptions. -- David Jones

Working...