我正在尝试使用sed
来替换大型配置文件中的字符串,但由于自动化要求,它需要通过脚本来完成。
目前这是我的测试文件 -
# The below line should get modified.
var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io'];
这是我目前的剧本摘录——
#/bin/bash
ORIGINSORIGINAL="var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io'];"
ORIGINS="var HOSTED_VIEWER_ORIGINS = ['https://s3-host1.lab.example.com', 'https://s3-host1.prod.example.com', 'null', 'http://mozilla.github.io', 'https://mozilla.github.io'];"
sed -i "s@${ORIGINSORIGINAL}@${ORIGINS}@g" /tmp/sedtest.txt
由于某种原因,字符串未与sed
匹配,并且未进行替换。我是否缺少一些明显的东西,或者我是否需要转义sed
命令的一部分,因为原始字符串中包含单引号。
谢谢!
一个简单的解决方案:
$: ORIGINSORIGINAL="var HOSTED_VIEWER_ORIGINS = .*" # no metas
$: ORIGINS="var HOSTED_VIEWER_ORIGINS = ['https://s3-host1.lab.example.com', 'https://s3-host1.prod.example.com', 'null', 'http://mozilla.github.io', 'https://mozilla.github.io'];"
$: sed "s@${ORIGINSORIGINAL}@${ORIGINS}@g" /tmp/sedtest.txt
var HOSTED_VIEWER_ORIGINS = ['https://s3-host1.lab.example.com', 'https://s3-host1.prod.example.com', 'null', 'http://mozilla.github.io', 'https://mozilla.github.io'];
事实证明,单引号字符串不是问题,但实际上是未正确转义的方括号。
将我的脚本更改为此(转义括号并进行更一般的搜索(就像一个魅力。
#/bin/bash
ORIGINSORIGINAL="var HOSTED_VIEWER_ORIGINS = [.*];"
ORIGINS="var HOSTED_VIEWER_ORIGINS = ['https://s3-host1.lab.example.com', 'https://s3-host1.prod.example.com', 'null', 'http://mozilla.github.io', 'https://mozilla.github.io'];"
sed -i "s@${ORIGINSORIGINAL}@${ORIGINS}@g" /tmp/sedtest.txt