dag*_*da1 4 string here-document
假设我想在某处有一个多行字符串的模板:
I have some
text with ${placeholders}
in this and some ${different}
ones ${here} and ${there}
Run Code Online (Sandbox Code Playgroud)
用用户输入替换占位符的最佳方法是什么?here-documents 会很好用吗?
假设[a]没有 \<newline>,也没有字符\, $, or`用于多行字符串(或者它们被正确引用),则此处文档(和变量)是您的最佳选择:
#!/bin/sh
placeholders="value one"
different="value two"
here="value three"
there="value four"
cat <<-_EOT_
I have some
text with ${placeholders}
in this and some ${different}
ones ${here} and ${there}.
_EOT_
Run Code Online (Sandbox Code Playgroud)
如果执行:
$ sh ./script
I have some
text with value one
in this and some value two
ones value three and value four.
Run Code Online (Sandbox Code Playgroud)
当然,正确地使用 qouting,即使是一个变量也可以:
$ multilinevar='I have some
> text with '"${placeholders}"'
> in this and some '"${different}"'
> ones '"${here}"' and '"${there}"'.'
$ echo "$multilinevar"
I have some
text with value one
in this and some value two
ones value three and value four.
Run Code Online (Sandbox Code Playgroud)
两种解决方案都可以接受多行变量占位符。
[a]来自手册:
... 字符序列 \<newline> 被忽略,并且必须使用 \ 来引用字符 \、$ 和 `。...
给定用户输入one, two,three
以下命令将${placeholder}用您的输入替换给定的所有实例:
sed -i 's/${placeholders}/one/g; s/${different}/two/g; s/${here}/three/g' yourTemplateFile
Run Code Online (Sandbox Code Playgroud)
如果您在 bash 脚本中使用它并在 shell 变量中输入用户输入,那么这将在一个命令中完成所有替换。