Home > Enterprise >  sed replacing string with special characters
sed replacing string with special characters

Time:09-24

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.

CodePudding user response:

Following script should work for you:

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

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

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

Note that you will need to escape tilde as \' in double quotes and also you are using $key to populate escappedValue by mistake.

Output:

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