假设我想在某个地方有一个多行字符串的模板:
I have some
text with ${placeholders}
in this and some ${different}
ones ${here} and ${there}
用用户输入替换占位符的最佳方法是什么?这里的文档有什么用处吗?
答案1
假设[a]多行字符串中没有使用 \<newline> 或字符\
, $
, 或`
(或者它们被正确引用),则此处文档(和变量)是您的最佳选择:
#!/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> 被忽略,并且必须使用 \ 来引用字符 \、$ 和 `。 ...
答案2
这是在 bash 中执行此操作的一种方法。您需要最新版本,因为我在这里依赖关联数组
template=$(cat << 'END_TEMPLATE'
I have some
text with ${placeholders}
in this and some ${different}
ones ${here} and ${there}
END_TEMPLATE
)
mapfile -t placeholders < <(grep -Po '(?<=\$\{).+?(?=\})' <<< "$template" | sort -u)
declare -A data
for key in "${placeholders[@]}"; do
read -p "Enter the '$key' value: " -r data[$key]
done
t=$template
while [[ $t =~ '${'([[:alnum:]_]+)'}' ]]; do
t=${t//"${BASH_REMATCH[0]}"/"${data[${BASH_REMATCH[1]}]}"}
# ^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# | + the value the user entered
# + the placeholder in the text
done
echo "$t"
答案3
给定用户输入one
, two
,three
以下命令将${placeholder}
用您的输入替换给定的所有实例:
sed -i 's/${placeholders}/one/g; s/${different}/two/g; s/${here}/three/g' yourTemplateFile
如果您在 bash 脚本中使用它并在 shell 变量中输入用户输入,那么这将在一个命令中完成所有替换。
答案4
使用以下脚本进行测试并且工作正常
echo "enter count of userinput required"
read c
for ((i=1;i<=$c;i++))
do
echo "enter the values"
read input_$i
done
awk -v i="$input_1" -v j="$input_2" -v k="$input_3" -v l="$input_4" '{gsub(/\${placeholders}/,i,$0);gsub(/\${different}/,j,$0);gsub(/\${here}/,k,$0);gsub(/\${there}/,l,$0);print $0}' filename >>filename_tmp && mv filename_tmp filename