Edit the file and replace the Hex value with Bash script

88 Views Asked by At

I have several larger files (400-800MiB) in which I need to convert Hex values to others. I can do this in some Hex editor, but I would like to do it automatically, in a Bash script.

I know how to check with xxd whether a given value is in a file:

FILE='file.vpk'
SEARCH_STRING='MaxRagdollCount'
OLD_HEX_VALUE="$( echo -n "$SEARCH_STRING" | xxd -p )"
HEX_VALUE=($( xxd -p "$FILE" | grep -E -o "${OLD_HEX_VALUE}222022[0-9]{,2}22" ))
echo "$HEX_VALUE"

but I can't figure out how to edit it.

I need to replace the value of

MaxRagdollCount" "any_number"

(4d6178526167646f6c6c436f756e742220223222)

with

MaxRagdollCount" "9"

(4d6178526167646f6c6c436f756e742220223922).

1

There are 1 best solutions below

2
Cloudlady On

Assuming the "any number" is always a single digit number (i.e. two hexadecimal characters) the following should work:

FILE='file.vpk'
SEARCH_STRING='MaxRagdollCount'
SEARCH_STRING_HEX="$(echo -n "$SEARCH_STRING" | xxd -p -c 0)"
#
# Convert binary to ascii:
xxd -p -c 0 $file > ${FILE}.tmp
#
# Replace every occurrence of "SEARCH_STRING_HEX<double quote><space><double quote><character><character><double quote>" with "SEARCH_STRING_HEX<double quote><space><double quote>39<double quote>".
sed -e "s/${SEARCH_STRING_HEX}222022..22/${SEARCH_STRING_HEX}2220223922/g" < ${FILE}.tmp > ${FILE}.tmp2
xxd -r -p ${FILE}.tmp2 > $FILE
rm -f ${FILE}.tmp ${FILE}.tmp2