title: Bash - quoted variable expansion mixed with sed yields bad substitution
body: <p>I have problem with this sed oneliner</p>
  
  <pre><code>sed -i -n "1h; 1!H; ${g; :a s/\(Name=\"$key\".*&lt;\!\[CDATA\[\"\)$val\(\"\]\]&gt;\)/\1$deval\2/;ta p}"
  </code></pre>
  
  <p>Obviously I need to expand variable <code>key</code>, <code>val</code> and <code>deval</code> in sed. So I need the <code>"</code> around sed command.</p>
  
  <p>With this command I get </p>
  
  <p><code>bash: !H: event not found</code></p>
  
  <p>escaping the <code>!</code> corrects it</p>
  
  <pre><code>sed -i -n "1h; 1\!H; ${g; :a s/\(Name=\"$key\".*&lt;\!\[CDATA\[\"\)$val(\"\]\]&gt;\)/\1$deval\2/;ta p}"
  </code></pre>
  
  <p>With this I get </p>
  
  <p><code>bash: sed -i -n "1h; 1\!H; ${g; :a s/\(Name=\"$key\".*&lt;\!\[CDATA\[\"\)$val\(\"\]\]&gt;\)/\1$deval\2/;ta p}" :bad substitution</code></p>
  
  <p>So I guess the <code>{</code> is a problem. Trying to fix it like this</p>
  
  <p><code>sed -i -n "1h; 1\!H; $\{g; :a s/\(Name=\"$key\".*&lt;\!\[CDATA\[\"\)$val(\"\]\]&gt;\)/\1$deval\2/;ta p}"</code></p>
  
  <p>yields </p>
  
  <p><code>sed: -e expression 1, char 6: unknown command: "\"</code></p>
  
  <p>What is going on here? How can I make this work?</p>