如何取代占位符的价值

时间:2016-06-03 05:32:05

标签: linux bash shell

我是shell编程新手。我有两个文件:

  1. eg.txt
  2. file.sh
  3. eg.txt文件包含一些HTML内容,file.sh包含一个shell脚本。 在脚本中,为temp变量分配了一个值,该值应该注入HTML文件。

    eg.txt

    <html>
      Hi MGM ,<br/>
      One alert has been received !!<br/>
    
     Here is the event Data.<br/><br/>
    
     <font size=‘1’>{temp}</font>
     <br/><br/>
     Regards,
     WDTS Supports.
     </html>
    

    file.sh

    echo $1
    temp=56
    
    (
    echo "To:"$1
    echo "Subject: Alert Updates !! "
    echo "Content-Type: text/html"
    
    echo cat eg.txt
    ) | /usr/sbin/sendmail -t
    
    echo "Mail sent !!"
    

3 个答案:

答案 0 :(得分:3)

使用sed:

sed "s/{temp}/$temp/" eg.txt | /usr/sbin/sendmail -t

您还可以使用printf在模板中注入变量:

<强> file.sh

temp=56
tpl=$(cat "eg.txt")

printf "$tpl" "$1" "$temp" | /usr/sbin/sendmail -t

<强> eg.txt

To:%s
Subject: Alert Updates !!
Content-Type: text/html

<html>
  Hi MGM ,<br/>
  One alert has been received !!<br/>

 Here is the event Data.<br/><br/>

 <font size=‘1’>%s</font>
 <br/><br/>
 Regards,
 WDTS Supports.
 </html>

<强>更新

如果有多个变量,只需编写多个替换命令(并在eg.txt中更新占位符):

sed "s/{temp1}/$temp1/;s/{temp2}/$temp2/" eg.txt | /usr/sbin/sendmail -t

答案 1 :(得分:2)

我已经为您的代码引入了一些错误检查:

#!/bin/bash
temp=56
if [ -z "$1" ]
then
echo "Usage : ./file.sh user_name_to_mail to"
exit -1
else
    if id "$1" >/dev/null 2>&1 #Check if user exists, suppress stdout, stderr
    then
      mail_header=$(echo -e "To: $1\nSubject: Alert Updates"'!!'"\nContent-Type: text/html\n")
      mail_body=$(awk -v var="$temp" '{print gensub(/{temp}/,var,"g"$0)}' eg.txt)
      echo -e "$mail_header\n$mail_body" | sendmail -t                   
    else
      echo -e "Sorry! Invalid User\n"
      exit -1 # The error code is set to  detect failure
    fi
fi

要防止邮件发送垃圾邮件,您需要为您要发送电子邮件的域名提供有效的SPF记录。检查[ this ]是否有起点。

注意:

!是bash的特殊字符,用于引用上一个命令。要解决此问题,我使用了..Updates"'!!'"\nContent-Type..

在单引号内,!失去了它的特殊含义。

有趣的读物:

  1. 什么是[ SPF ]记录?
  2. 打开SPF [ documentation ]

答案 2 :(得分:1)

echo $1
temp=56

    (
    echo "To:"$1
    echo "Subject: Alert Updates !! "
    echo "Content-Type: text/html"

    awk -F "" -v var=$temp '{gsub(/{temp}/,var,$0); print}' < eg.txt 
) | /usr/sbin/sendmail -t

echo "Mail sent !!"

将awk添加到'|'其中temp存储在awk变量中: var ,后来被替换

awk -F "" -v var=$temp '{gsub(/{temp}/,var,$0); print}'