pbyfire has asked for the wisdom of the Perl Monks concerning the following question:

After much research and trying examples of pack,unpack and hex editing I still cannot edit a binary file.

In the example below I need a perl routine to change all instances of the ASCII string "P200000976" in a binary file to read "Test123456" by replacing the hex values that define the target string (50 32 30 30 30 30 30 39 37 36) with values that represent the replacement string (54 65 73 74 31 32 33 34 35 36).

00002A00   00 00 00 00  00 00 00 00  00 00 00 00  00 00 01 80  00 0A 50 32  30 30 30 30  30 39 37 36  00 00 00 01  ..................P200000976....

Replies are listed 'Best First'.
Re: binary edit
by BrowserUk (Patriarch) on Apr 24, 2012 at 18:02 UTC

    You're trying too hard. You don't need pack, unpack or "hex editing".

    Update: As pointed out by dave_the_m below, I mixed up my options: Switched -n for -p

    This should work if you're on Windows:

    perl -ple"binmode*ARGV if $.==1; s[P200000976][Test123456]g;" <infile +>outfile

    Or this if you're on *nix:

    perl -ple's[P200000976][Test123456]g;' <infile >outfile

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

      Thank you for the rapid reply, unfortunately the example(s) did not work for me. It left the outfile empty. The only way I can see the string to be replaced is with a hex editor.

      I am working on a *nix system and use vi all day long and I can only see the hex value and the ascii value of the string in vi calling xxd.

        replace the -nle with -pe and it should work

        Dave.

        Tested using -pe rather than -nle as the -p flag does an implicit print whereas -n does not.

        knoppix@Microknoppix:~$ perl -E '$str .= chr int rand 256 for 1 .. 100 +00; print $str; substr $str, 4809, 10, q{P200000976}^C> xxxxx knoppix@Microknoppix:~$ perl -E ' > $str .= chr int rand 256 for 1 .. 10000; > substr $str, 4809, 10, q{P200000976}; > print $str;' > orig knoppix@Microknoppix:~$ hexdump -C orig | egrep '12[cd]0' 000012c0 29 72 ff 9b 1d bf 35 39 3d 50 32 30 30 30 30 30 |)rÿ..¿59= +P200000| 000012d0 39 37 36 43 4c 6d 90 9e 07 03 bb 42 32 c9 b5 ff |976CLm... +.»B2ɵÿ| knoppix@Microknoppix:~$ perl -pe 's{P200000976}{Test123456}' < orig > +modified knoppix@Microknoppix:~$ hexdump -C modified | egrep '12[cd]0' 000012c0 29 72 ff 9b 1d bf 35 39 3d 54 65 73 74 31 32 33 |)rÿ..¿59= +Test123| 000012d0 34 35 36 43 4c 6d 90 9e 07 03 bb 42 32 c9 b5 ff |456CLm... +.»B2ɵÿ| knoppix@Microknoppix:~$

        Cheers,

        JohnGG