【问题标题】:Replace the string content in sed with special chars用特殊字符替换 sed 中的字符串内容
【发布时间】:2015-01-27 23:02:10
【问题描述】:

我有这样的代码:

sed "s/TEST_CASES_R/$testCaseLocations/g" template >> newfile

其中$testCaseLocations 具有,tests/test/,tests/test/2。所以这条线失败了:

替代命令中的错误标志

我该如何解决这个问题?

【问题讨论】:

标签: bash shell sed


【解决方案1】:

啊,sed 代码注入。 sed 看到的是

sed "s/TEST_CASES_R/,tests/test/,tests/test/2/g" template >> newfile

...这是荒谬的。根本问题是 sed 无法区分您希望它作为数据看到的东西——$testCaseLocations 的内容——和指令。

我认为最好的解决方案是使用 awk:

awk -v replacement="$testCaseLocations" '{ gsub(/TEST_CASES_R/, replacement); print }' template >> newfile

因为通过不将testCaseLocations 视为代码,这巧妙地回避了代码注入问题。在这种特殊情况下,您还可以为 sed 使用不同的分隔符,例如

 sed "s@TEST_CASES_R@$testCaseLocations@g" template >> newfile

但是,如果$testCaseLocations 包含@,或者如果它包含在其出现的上下文中对sed 有意义的字符,例如\&,您就会遇到麻烦。

【讨论】:

  • 感谢 awk 解决方案。整洁的一个。
  • Gsub 默认为 $0,因此不需要最后一个参数。
【解决方案2】:

只需为sed 使用另一个分隔符,否则它会看到很多斜线:sed 's#hello#bye#g' 很好。

在你的情况下:

sed "s#TEST_CASES_R#$testCaseLocations#g" template >> newfile

查看另一个测试:

$ var="/hello"
$ echo "test" | sed "s/test/$var/g"
sed: -e expression #1, char 9: unknown option to `s'
$ echo "test" | sed "s#test#$var#g"
/hello

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    相关资源
    最近更新 更多