sed 用特殊字符替换字符串

sed replacing string with special characters

令人惊讶的是,类似的问题已被多次询问,但 none 的解决方案适用于我的用例 - 即替换可包含所有可能的特殊字符的字符串。

在文本文件中,即

 hello.txt

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

还有一个shell脚本

 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

预期结果

hello.txt

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

但是run.sh中的上述sed cmd 不起作用。我也试过:

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

来自:Replacing special characters in a shell script using sed

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

来自:Escape a string for a sed replace pattern

但两者都不起作用。

以下脚本应该适合您:

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

请注意,您需要将波浪号转义为双引号中的 \',而且您使用 $key 错误地填充了 escappedValue

输出:

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