2564741
#!/bin/bash
2564741
2564741
function patch_strings_in_file()
2564741
{
2564741
    local FILE="$1"
2564741
    local PATTERN="$2"
2564741
    local REPLACEMENT="$3"
2564741
2564741
    # Find all unique strings in FILE that contain the pattern
2564741
    STRINGS=$(strings ${FILE} | grep ${PATTERN} | sort -u -r)
2564741
2564741
    if [ "${STRINGS}" != "" ] ; then
2564741
        echo "File '${FILE}' contain strings with '${PATTERN}' in them:"
2564741
2564741
        for OLD_STRING in ${STRINGS} ; do
2564741
            # Create the new string with a simple bash-replacement
2564741
            NEW_STRING=${OLD_STRING//${PATTERN}/${REPLACEMENT}}
2564741
2564741
            # Create null terminated ASCII HEX representations of the strings
2564741
            OLD_STRING_HEX="$(echo -n ${OLD_STRING} | xxd -g 0 -u -ps -c 256)00"
2564741
            NEW_STRING_HEX="$(echo -n ${NEW_STRING} | xxd -g 0 -u -ps -c 256)00"
2564741
2564741
            if [ ${#NEW_STRING_HEX} -le ${#OLD_STRING_HEX} ] ; then
2564741
                # Pad the replacement string with null terminations so the
2564741
                # length matches the original string
2564741
                while [ ${#NEW_STRING_HEX} -lt ${#OLD_STRING_HEX} ] ; do
2564741
                    NEW_STRING_HEX="${NEW_STRING_HEX}00"
2564741
                done
2564741
2564741
                # Now, replace every occurrence of OLD_STRING with NEW_STRING
2564741
                echo -n "Replacing ${OLD_STRING} with ${NEW_STRING}... "
2564741
                hexdump -ve '1/1 "%.2X"' ${FILE} | \
2564741
                sed "s/${OLD_STRING_HEX}/${NEW_STRING_HEX}/g" | \
2564741
                xxd -r -p > ${FILE}.tmp
2564741
                chmod --reference ${FILE} ${FILE}.tmp
2564741
                mv ${FILE}.tmp ${FILE}
2564741
                echo "Done!"
2564741
            else
2564741
                echo "New string '${NEW_STRING}' is longer than old" \
2564741
                     "string '${OLD_STRING}'. Skipping."
2564741
            fi
2564741
        done
2564741
    fi
2564741
}
2564741
2564741
patch_strings_in_file $@