用另一个文件的内容替换文件中的关键字的shell脚本

Jem*_*Jem 5 shell sed sh find-and-replace

我将创建一个 .sh 以使用其他文件的内容替换文件中的特定关键字。

  • template.html 包含一个唯一的字符串“ PLACEHOLDER
  • 它必须替换为文件“contents.html”的内容

sed 可用于替换关键字:

value="hello superuser"
sed -e "s/__PLACEHOLDER__/${value}/g" template.html > page.html
Run Code Online (Sandbox Code Playgroud)

所以我尝试了以下方法:

value=$(<contents.html)
sed -e "s/__PLACEHOLDER__/${value}/g" template.html > page.html
Run Code Online (Sandbox Code Playgroud)

并收到以下错误消息:替代模式内未转义的换行符

请问这种情况怎么处理?

谢谢!

gle*_*man 6

使用 bash,你可以这样写:

templ=$(<template.html)
value=$(<contents.html)
echo "${templ//__PLACEHOLDER__/$value}" > page.html
Run Code Online (Sandbox Code Playgroud)

  • 不正确: `tmpl="foo__PLACEHOLDER__bar"; value='with/and}too'; echo "${tmpl//__PLACEHOLDER__/$value}"` 按预期工作 (2认同)