【问题标题】:sed replacing string with special characterssed 用特殊字符替换字符串
【发布时间】: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


    【解决方案1】:

    以下脚本应该适合您:

    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$`{}[]|%';"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 2021-06-11
      • 1970-01-01
      相关资源
      最近更新 更多