简体   繁体   中英

replace a key in a file by a sentence with spaces and special characters

I searched a means to replace an identified key in a file html by an sentence with spaces and special characters. I tried to use sed but I'd get many errors because the sentence may contains many characters.

My shell script :

 ...
 cp $HTML_TEMPLATE $HTML_OUTPUT
 sed "s/\@mail_title/$HTML_TITLE/g" $HTML_OUTPUT > temp && mv -f temp $HTML_OUTPUT
 sed "s/\@mail_body/$HTML_CONTENT/g" $HTML_OUTPUT > temp && mv -f temp $HTML_OUTPUT
 ...

The goal is to replace in mail.html two keys ( @mail_body and @mail_title ) by 2 text variables ( BODY_HTML_TITLE="Report Statistics -$(date +'%Y-%m-%d')" and BODY_HTML_CONTENT="test" ) with the script.

mail.html :

....
<table id="container" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td>
      <!-- Header -->
      <table id="header">
       <tr>
         <td>
           <table width="100%">
           <tr>
             <td width="50%" align="right" style="font-size:15px; line-height:18px; color:#b5397a; font-family:Helvetica, Arial, sans-serif;"> <h2>@mail_title</h2></td>

              </tr>
              ...                                                  

I see that your question has following sed statements:

sed "s/\@mail_title/$HTML_TITLE/g" $HTML_OUTPUT > temp && mv -f temp $HTML_OUTPUT
sed "s/\@mail_body/$HTML_CONTENT/g" $HTML_OUTPUT > temp && mv -f temp $HTML_OUTPUT

However, the target variables (BODY_HTML_TITLE & BODY_HTML_TITLE) that you're mentioning below are different from what you've mentioned in the sed lines (HTML_TITLE & HTML_CONTENT):

BODY_HTML_TITLE="Report Statistics -$(date +'%Y-%m-%d')"
BODY_HTML_CONTENT="test"

Is it a typo in your script? My test script works perfectly fine when i'm using the correct variables:

[gc@slave1 ~]$ cat file
HTML_TITLE="Report Statistics -$(date +'%Y-%m-%d')"
echo $HTML_TITLE

<tr>
     <td Arial, sans-serif;"> <h2>@mail_title</h2></td>
</tr>


[gc@slave1 ~]$ cat main
sed "s/@mail_title/$HTML_TITLE/g" file


[gc@slave1 ~]$ ./main
HTML_TITLE="Report Statistics -$(date +'%Y-%m-%d')"
echo $HTML_TITLE

<tr>
     <td Arial, sans-serif;"> <h2>Report Statistics -2014-08-05</h2></td>
</tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM