【问题标题】:sed: Bad flag in substitute command '('sed:替换命令中的错误标志“(”
【发布时间】:2018-03-14 17:19:31
【问题描述】:

我正在尝试将占位符 ${SNIPPET} 替换为 js 文件的内容。我很难理解我收到的错误。

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

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

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

【问题讨论】:

  • 您需要在 js 文件中转义斜杠。
  • 您是否建议用一些 sed 替换 cat sn-p.js 以用转义斜杠替换斜杠?
  • 在不知道$SNIPPET 的值或snippet.js 的内容的情况下,这一切都将是猜测......但这可能与Replace a word with multiple lines using sed? 或其任何一个中描述的问题相同链接的重复项。
  • 没有 $SNIPPET 变量。有一个占位符字符串“${SNIPPET}”。 sn-p.js 作为后缀 .js 表示一个 javascript 文件,必须考虑它包含您在 js 文件中可能拥有的所有可能的字符。我尝试了删除换行符的解决方案,但没有奏效@glennjackman 实际上是正确地指出斜线是问题

标签: shell sed


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-28
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多