1

i want to replace some occurrence in a bin file. for exemple

file.bin content :

0A0A0A0A954654370B0B0B0B
0A0A0A0A453426540B0B0B0B

I want to modify the content between 0A0A0A0A and 0B0B0B0B without care of the original content and replacing with 0A0A0A0A12345678B0B0B0B in each line

i use perl regex command : perl -pi -e 's|\x0A\x0A\x0A\x0A\x95\x46\x54\x37\x0B\x0B\x0B\x0B|\x0A\x0A\x0A\x0A\x12\x34\x56\x78\xB0\xB0\xB\x0B|g' /file.bin

but how to tell perl to ignore the content between 0A and 0B in source section to use one command for the all content of file ?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Labure
  • 11
  • 1
  • 1
    I've never done regex on binary content but I would try to replace `\x95\x46\x54\x37` by `.{4}` meaning any char 4 times. If it doesn't work due to the length, you could also try `.+?` which means any char 1 or N times but in an ungreedy way, so that it doesn't "eat" to many chars and stops when it finds `\x0B\x0B\x0B\x0B`. – Patrick Janser May 17 '21 at 10:35

1 Answers1

3

First of all, note that you used \xB0\xB0\xB\x0B instead of \x0B\x0B\x0B\x0B.


Next, we have to cover a problem with the approach being taken.

Since you say it's a binary file, and since you're using \x0A, I'm assuming 0A represents the single byte with that hex value.

If so, 0A is presumed to be a line feed by Perl. The substitution is applied to each of these in turn:

0A
0A
0A
0A
954654370B0B0B0B0A
0A
0A
0A
453426540B0B0B0B

Your pattern never matches, so no substitution occurs.

This could be resolved by reading the entire file at once using -0777.

perl -i -0777pe's{\x0A\x0A\x0A\x0A\x95\x46\x54\x37\x0B\x0B\x0B\x0B}
                 {\x0A\x0A\x0A\x0A\x12\x34\x56\x78\x0B\x0B\x0B\x0B}g'

Finally, on to the question you asked.

. matches any character other than 0A. But . with /s matches any character, period. So you could use .... (with /s), or .{4} (with /s).

perl -i -0777pe's{\x0A\x0A\x0A\x0A.{4}\x0B\x0B\x0B\x0B}
                 {\x0A\x0A\x0A\x0A\x12\x34\x56\x78\x0B\x0B\x0B\x0B}sg'

or

perl -i -0777pe's/\x0A\x0A\x0A\x0A\K.{4}(?=\x0B\x0B\x0B\x0B)/\x12\x34\x56\x78/sg'
ikegami
  • 367,544
  • 15
  • 269
  • 518