1

I have a binary file type (many instances of these files) where I would like to replace the string "DC-GX850" with "DMC-GX95". Fortunately the two strings are of equal length. The files may be as large as 22MB. Typically the string occurs twice in the file, within the first 1000 bytes. both need to be replaced.

My operating system is MacOS 10.14.6, running standard BASH.

I have two parts of the solution working, but I am unable to combine them. For my test case, the source file is P1000047.RW2, and the modified file is P1000047D.RW2; "44434d2d47583835" is the hex representation of "DMC-GX95"; 3a4 and 10f0 are the file offsets for the start of the strings for this instance of the file; other files may have different offsets.

This code correctly patches the file:

echo "3a4: 44434d2d47583835" | xxd  -r - P1000047D.RW2
echo "10f0: 44434d2d47583835" | xxd  -r - P1000047D.RW2

This code produces the two strings needed for the patch:

strings -t x P1000047.RW2 | grep "DC-GX850" | sed s/\ DC-GX850/:\ 44434d2d47583835/

Result:

3a4: 44434d2d47583835
10f0: 44434d2d47583835

However, when I try to combine the two, this code only executes the first patch

strings -t x P1000047.RW2 | grep "DC-GX850" | sed s/\ DC-GX850/:\ 44434d2d47583835/ | xxd  -r - P1000047D.RW2

I've tried using sed with the -n option but still unable to get it to work.

I could of course write the script as a loop, but I'd like to avoid that if possible. Any suggestions?

1 Answer 1

3

Just use perl which works happily with binary files:

perl -pi -e 's/DC-GX850/DMC-GX95/g' ./*.RW2

Or if you only want to do the substitution in the first 1000 bytes of the files:

perl -pi -e '
  BEGIN {$/ = \1000} # records are 1000 byte blocks instead of lines
  s/DC-GX850/DMC-GX95/g if $. == 1; # substitute in first record only
  close ARGV if eof # to reset $. between files' ./*.RW2

With -i, the files are modified in place (actually, replaced by the modified copy), change to -i.orig to preserve the original with a .orig extension.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .