【发布时间】:2021-11-17 03:40:28
【问题描述】:
令人惊讶的类似问题已被多次询问,但没有一个解决方案适用于我的用例 - 即替换可以包含所有可能的特殊字符的字符串。
在文本文件中,即
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/[][\\^*+.$-]/\\\1/g'
来自:Replacing special characters in a shell script using sed
sed -e 's/[\/&]/\\&/g'
来自:Escape a string for a sed replace pattern
但两者都不起作用。
【问题讨论】:
标签: string bash shell sed replace