-4

I am trying to replace a string from shell. I have already read the string and it's in template variable. Now I am trying to replace the companyId which store in REPLACE_COMPANY variable with the parameter passed in shell. I have tried few solution from net but didn't succeeded. Also I want to keep the file format intact as with replace I found all string comes into one line. Can anyone help.

REPLACE_COMPANY="companyId" 
echo "$template" 
##### Company: companyId CONFIG  START #####

backend FE:spaces-companyId
        redirect scheme https if !{ ssl_fc }
        balance roundrobin
        server 1-www spacesIp:80 check cookie s2

backend BE:synapse-companyId
         redirect scheme https if !{ ssl_fc }
         balance roundrobin
         server 1-www synapseIp:8008 check cookie s2

##### Company: companyId CONFIG  END ##### 
SLePort
  • 15,211
  • 3
  • 34
  • 44
Souvik
  • 1,219
  • 3
  • 16
  • 38
  • 2
    It is confusing. Do you just need `sed -i "/companyld/\$template/ filename` so you end up with `REPLACE_COMPANY="$template"` ? Is that your goal? – David C. Rankin May 08 '16 at 10:03
  • 2
    can you provide expected result ? – monk May 08 '16 at 10:12
  • Hi Expected goad is, all the text (avaiable in $template) where companyId(Declared in $REPLACE_COMPANY) is mentioned will be replaced with the parameter I passed in $1 of shell and will be stored in a variable again. Also the formatting will remain same.I don't want to write it directly to any file first as other works needs to be done. – Souvik May 08 '16 at 13:04

2 Answers2

0

You can use envsubst to replace variable references in files with the values available in the current shell. For example:

$ cat test.template
Hi $USER
$ envsubst < test.template
Hi username
l0b0
  • 55,365
  • 30
  • 138
  • 223
0

It's done from my side. Please find the code below. Thanks for all the helps.

Note: INF contains the file name which contains the template which needs to be modifies and write back. and $FILE contains where the final output need to be written.

provision(){
   INF="proxy.template"
   REPLACE_COMPANY="companyId"
   REPLACE_SPACEIP="spacesIp"
   REPLACE_SYNAPSEIP="synapseIp"
   sed -e "s/$REPLACE_COMPANY/$1/g" -e "s/$REPLACE_SPACEIP/$2/g" -e "s/$REPLACE_SYNAPSEIP/$3/g" $INF > $1
   cat $1 >> $FILE
   rm $1
}
Souvik
  • 1,219
  • 3
  • 16
  • 38
  • This won't work if any of your strings to be replaced have characters that don't translate to themselves as regexes, or if your replacement strings contain `/`s. – Charles Duffy May 08 '16 at 19:21
  • See BashFAQ #21 -- http://mywiki.wooledge.org/BashFAQ/021 -- for more reliable alternatives. – Charles Duffy May 08 '16 at 19:21