sed:替换命令中的坏标记'('

时间:2018-03-14 17:19:32

标签: shell sed

我试图用js文件的内容替换占位符$ {SNIPPET}。我很难理解我收到的错误。

sed  -e "s/\${SNIPPET}/$(cat snippet.js)/" ../../handlebars/templates/bootstrap-template.hbs

错误:替换命令中的错误标志:'('

寻找可跨平台工作的解决方案(OSX / Linux)

1 个答案:

答案 0 :(得分:1)

使用这些测试文件

$ cat snippet.js
hello/(world)
$ cat template.hbs
foo
${SNIPPET}
bar

我可以(有点)复制你的错误(我有GNU sed 4.2.2):

$ sed "s/\${SNIPPET}/$(cat snippet.js)/" template.hbs
sed: -e expression #1, char 20: unknown option to `s'

你可以这样做,它会转义斜杠(它是s///命令的分隔符)

sed "s/\${SNIPPET}/$(sed 's,/,\\/,g' snippet.js)/" template.hbs
foo
hello/(world)
bar

或者,如果SNIPPET占位符就像我拥有它一样,你可以使用其他sed命令:

sed '/\${SNIPPET}/{
    # read the file into the stream
    r snippet.js
    # delete SNIPPET line
    d
}' template.hbs
foo
hello/(world)
bar

又一种方法

j=$(<snippet.js)   # read the file: `$(<...)` is a bash builtin for `$(cat ...)`
sed "s/\${SNIPPET}/${j//\//\\\/}/" template.hbs