title: Using sed to replace string in file with contents of variable of that name
body: <p>I'm trying to use sed to replace template strings in files of the form %XXX% with the value of a variable called XXX in my shell script.</p>
  
  <p>e.g. The following works perfectly</p>
  
  <pre><code>sed "s/%user_home%/$user_home/gi"
  </code></pre>
  
  <p>So if <code>user_home=fred</code> the following,</p>
  
  <pre><code>NameVirtualHost *:80
  
  &lt;VirtualHost *:80&gt;
    ServerName %server_name%
  
    ErrorLog /var/log/apache2/%user_home%_webapp_error.log
    CustomLog /var/log/apache2/%user_home%_webapp.log common
  
    DocumentRoot /home/%user_home%/web_app/public
  &lt;/VirtualHost&gt;
  </code></pre>
  
  <p>becomes,</p>
  
  <pre><code>NameVirtualHost *:80
  
  &lt;VirtualHost *:80&gt;
    ServerName %server_name%
  
    ErrorLog /var/log/apache2/fred_webapp_error.log
    CustomLog /var/log/apache2/fred_webapp.log common
  
    DocumentRoot /home/fred/web_app/public
  &lt;/VirtualHost&gt;
  </code></pre>
  
  <p>The problem is that I want to run the sed command without explicitly knowing the template strings and their variables up front. That is, it looks for %XXX% and then replaces that with the contents of $XXX without caring what the actual name of the variable is.</p>
  
  <p>I know its got something to do with back-references but I can't figure out how to use the content of a back-reference as the variable name.</p>
  
  <p>I tried,</p>
  
  <pre><code>sed "s/%\([a-z_]\)%/$(\1)/gi"
  </code></pre>
  
  <p>but this failed to work because it seems to be a looking for a variable called $\1.</p>