Home:ALL Converter>sed replacing string with special characters

sed replacing string with special characters

Ask Time:2021-09-24T02:19:09         Author:Edison Lo

Json Formatter

Surprisingly similar questions had been asked multiple times but none of the solutions worked for my use case - which is to replace a string which can contains all possible special characters.

In a text file, i.e

 hello.txt

 ABC="12'{}34[];|^)(*&^!^#~`!-567"

And a shell script

 run.sh

 #!/bin/sh
 key="12'{}34[];|^)(*&^!^#~`!-567"
 escappedKey=$(printf '%s\n' "$key" | sed -e 's/[]\/$*.^[]/\\&/g');

 value="345$`{}[]|%';"
 escappedValue=$(printf '%s\n' "$value" | sed -e 's/[]\/$*.^[]/\\&/g');

 sed -i "s/$escappedKey/$escappedValue/g" hello.txt

Expected result in

hello.txt

ABC="345$`{}[]|%';"

But the above sed cmd in run.sh doesn't work. And I have also tried with:

sed -e 's/[][\\^*+.$-]/\\\1/g'

from: Replacing special characters in a shell script using sed

sed -e 's/[\/&]/\\&/g'

from: Escape a string for a sed replace pattern

but both doesn't work.

Author:Edison Lo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69305102/sed-replacing-string-with-special-characters
yy