gpt4 book ai didi

linux - 如何替换占位符的值

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:37 34 4
gpt4 key购买 nike

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

  1. 例如.txt
  2. 文件.sh

eg.txt 文件包含一些 HTML 内容,file.sh 包含一个 shell 脚本。在脚本中,一个值被分配给 temp 变量,该值应该被注入(inject)到 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>

文件.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 !!"

最佳答案

使用 sed :

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

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

文件.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

关于linux - 如何替换占位符的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37606618/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com