我有一个模板文件(template.txt
):
Hello, $x
Hello, $y
我有一个脚本文件(script.sh
):
#!/bin/bash
$x=linux
$y=unix
# I want to include template.txt as a here-doc
如何将template.txt
包含为script.sh
的here-doc
因此,当我运行script.sh
时,输出应该是:
Hello, linux
Hello, unix
编辑:
我认为replace
对我的工作来说是一个很好的命令:
$ cat template.txt | replace '$x' linux '$y' unix
一个更复杂的工具:
$ cheetah compile template.tmpl
$ x=linux y=unix python template.py --env
下面的bash函数将任意文件求值为here文档,允许bash用作迷你模板语言。它不需要任何临时文件。
#!/bin/bash
template() {
file=$1
shift
eval "`printf 'local %sn' $@`
cat <<EOF
`cat $file`
EOF"
}
变量将从环境中展开,或者可以直接传递,例如模板文件
Hello $x, $y, $z
和摘录
y=42
for i in 1 2; do
template template.txt x=$i z=end
done
输出将是
Hello 1, 42, end
Hello 2, 42, end
请注意,模板文件中的任意代码也将被执行,因此请确保您信任编写它的人。
我在一个项目中使用了这个函数。它从模板构建一个实际的here文档,然后使用.
:在当前shell中执行它
# usage: apply_template /path/to/template.txt
apply_template () {
(
trap 'rm -f $tempfile' EXIT
tempfile=$(mktemp $(pwd)/templateXXXXXX)
echo 'cat <<END_TEMPLATE' > $tempfile
cat $1 >> $tempfile
echo END_TEMPLATE >> $tempfile
. $tempfile
)
}
#!/bin/bash
x=linux
y=unix
cat << EOF
Hello, $x
Hello, $y
EOF
这可能对你有用(GNU sed):
cat <<! >template.txt
Hello, $x
Hello, $y
!
cat <<! >replace
export "$@"
sed -e '1icat <<EOT' -e '$aEOT' | sed ':a;$!{N;ba};e'
!
cat template.txt | replace x='Fred Flintstone' y='Barney Rubble'
Hello, Fred Flintstone
Hello, Barney Rubble
这是我提出的解决方案:
eval $'cat <<