title: Is it possible to escape regex metacharacters reliably with sed
body: <p>I'm wondering whether it is possible to write a 100% reliable <code>sed</code> command to escape any regex metacharacters in an input string so that it can be used in a subsequent sed command. Like this:</p>
  
  <pre><code>#!/bin/bash
  # Trying to replace one regex by another in an input file with sed
  
  search="/abc\n\t[a-z]\+\([^ ]\)\{2,3\}\3"
  replace="/xyz\n\t[0-9]\+\([^ ]\)\{2,3\}\3"
  
  # Sanitize input
  search=$(sed 'script to escape' &lt;&lt;&lt; "$search")
  replace=$(sed 'script to escape' &lt;&lt;&lt; "$replace")
  
  # Use it in a sed command
  sed "s/$search/$replace/" input
  </code></pre>
  
  <p>I know that there are better tools to work with fixed strings instead of patterns, for example <code>awk</code>, <code>perl</code> or <code>python</code>. I would just like to prove whether it is possible or not with <code>sed</code>. I would say let's concentrate on basic POSIX regexes to have even more fun! :)</p>
  
  <p>I have tried a lot of things but anytime I could find an input which broke my attempt. I thought keeping it abstract as <code>script to escape</code> would not lead anybody into the wrong direction.</p>
  
  <p>Btw, the discussion came up <a href="https://stackoverflow.com/questions/29606527/sed-replace-multiple-patterns-but-not-with-the-same-string/29609706?noredirect=1#comment47365660_29609706">here</a>. I thought this could be a good place to collect solutions and probably break and/or elaborate them.</p>