【发布时间】:2015-01-27 23:02:10
【问题描述】:
我有这样的代码:
sed "s/TEST_CASES_R/$testCaseLocations/g" template >> newfile
其中$testCaseLocations 具有,tests/test/,tests/test/2。所以这条线失败了:
替代命令中的错误标志
我该如何解决这个问题?
【问题讨论】:
我有这样的代码:
sed "s/TEST_CASES_R/$testCaseLocations/g" template >> newfile
其中$testCaseLocations 具有,tests/test/,tests/test/2。所以这条线失败了:
替代命令中的错误标志
我该如何解决这个问题?
【问题讨论】:
啊,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 有意义的字符,例如\ 或&,您就会遇到麻烦。
【讨论】:
只需为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
【讨论】: