複数行の文字列と文字列補間を処理する方法は?

複数行の文字列と文字列補間を処理する方法は?

どこかに複数行の文字列用のテンプレートを持ちたいとしましょう。

I have some
text with ${placeholders}
in this and some ${different}
ones ${here} and ${there}

プレースホルダをユーザー入力に置き換える最善の方法は何ですか?ここにある文書は役に立ちますか?

ベストアンサー1

\<newline> または文字 , , または が[a]複数行文字列に使用されていないか、正しく引用されていると仮定すると、このドキュメント(および変数)が最良の選択です。\$`

#!/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_

実行される場合:

$ sh ./script
I have some
text with value one
in this and some value two
ones value three and value four.

もちろん、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.

どちらのソリューションでも、複数行の変数プレースホルダを受け入れることができます。


[a]マニュアルから:

...文字シーケンス\ <newline>は無視され、\は\、$、および文字を引用するために使用する必要があります。 ...

おすすめ記事