我需要创建这个脚本,然后输出到 template.vars 中的 html 文件数据。该脚本是一个模板引擎,但现在它所做的只是从键盘输入输入,当输入为@NAME@ 时,在 template.vars 中回显名称。下面是目前模板引擎的代码:
#!/bin/bash
IFS=@ #makes @ a delimiter.
while read line
do
dataspace=$(awk '$0=$1' FS== <<< "$line")
value=$(awk '$0=$2' FS== <<< "$line")
printf -v $dataspace "$value" #make the value stored in value into the name of a dataspace.
done < 'template.vars' #read template.vars for standard input.
skipflag=false #initialize the skipflag to false
while read line #while it is reading standard input one line at a time
do
read -a dataspacearray <<< "$line" #make the line into an array.
if [ $skipflag == false ] && [ "${dataspacearray[1]}" != "ENDIF" ] ; then
if [[ ${dataspacearray[1]} == "IF "* ]] ; then #If second element of dataspacearray is "IF "(something)
dataspace=`echo ${dataspacearray[1]} | cut -d' ' -f2`
if [ -z "${!dataspace}" ] ; then #if dataspace not found, skip everything up to endif. -z to test string
skipflag=true
fi
else
for ((i=0; i<${#dataspacearray[@]}; i++))
do
dataspace=${dataspacearray[i]} #access to each dataspace in the array
even=`expr $i % 2`
if [ $even == '0' ] ; then #if it's even(f0,f2, f4.. etc. etc) then it's not a variable, so print it directly
if [ -n "${dataspace}" ] ; then
printf ${dataspace}
fi
else #(odd dataspaces(f1, f3... etc.) are variables, print their values if they exist
if [ -n "${!dataspace}" ] ; then
printf ${!dataspace}
else
printf "Error!!!"
fi
fi
done
printf "\n"
fi
else
skipflag=false
fi
done
html 文件作为输入输入,如下所示:
<html>
<head>
<title>@NAME@</title>
</head>
<body>
<p>Name: @NAME@</p>
<p>Major: @MAJOR@</p>
<p>Classification: @CLASS@</p>
<p>Graduation date: @GDATE@</p>
@IF HONORS@
<p>Graduating with Honors</p>
@ENDIF@
</body>
</html>
脚本使用 template.vars 文件中的数据替换所有以 @ 开头和结尾的字符串(或输出错误!!!如果未找到)。我见过很多例子,其中模板替换了开头有 $ 的任何文本,并且认为我需要实现类似的东西,但它会读取 html 文件作为输入,然后将其保存为输出。我该怎么做呢?