Perl searching and replacing an HEX pattern

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • duncanm817
    New Member
    • Mar 2008
    • 1

    Perl searching and replacing an HEX pattern

    hi,

    I require some assistance in understanding how to accomplish replacing a particular hex value in a binary file on aix.

    in a binary file I need to find the following combination:

    5A 00 10 D3 A9 XX XX XX XX XX XX XX XX XX XX XX XX 0C 5A
    XX represents any valid HEX value

    then replace this with the following HEX value
    5A 00 10 D3 A9 XX XX XX XX XX XX XX XX XX XX XX XX 5A

    I am trying to delete the 0C hex value from the binary file when it matches certain conditions:

    I tried the following command with spaces and without... it doesn't do anything.

    perl -pe 's/\x5A\x00\x10\xD 3\xA9\x[0-9a-fA-F]\{24\}\x0C\x5A/\x5A\x00\x10\xD 3\xA9\x[0-9a-fA-F]\{24\}\x5A/g' source > destination

    I viewed the source file in an HEX editor and it definately has 1 occurance of the HEX sequence
    5A 00 10 D3 A9 XX XX XX XX XX XX XX XX XX XX XX XX 0C 5A

    I would greatly appreciate any assistance

    regards,
    Duncan
  • nithinpes
    Recognized Expert Contributor
    • Dec 2007
    • 410

    #2
    perl -pe 's/^(5A\s00\s10\sD 3\sA9\s([0-9a-fA-F]{2}\s){12})0C\s (5A)/$1$3/g' source > destination

    I would like to clarify 3 things in your regex:
    1. Use \s for space.
    2. You have escaped '{' in \{24\} . This would mean actual {24} and not 24 instances.
    3. In [0-9a-fA-F]\{24\} , you are trying to match 24 continuous occurence of the hexadecimal characters. But, there is space after every two characters.
    In the above regex, I have grouped characters to make replacement easier with $!,$2 or $#.

    I am assuming you are on a linux machine. On Windows, single quotes need to be replaced with doublee quotes. Also, binary files need to be read and written using 'binmode'.

    Comment

    Working...