title: Escape characters in grep
body: <p>I'm a little confused about how many backslashes are needed to escape the alternation operator <code>|</code> in regular expressions for grep. This</p>
  
  <pre><code>echo abcdef | grep -e"def|zzz"
  </code></pre>
  
  <p>outputs nothing, because grep is not in extended regex mode. Escaping with one backslash works, </p>
  
  <pre><code>echo abcdef | grep -e"def\|zzz"
  </code></pre>
  
  <p>prints <code>abcdef</code>. More surprisingly, escaping with 2 backslashes also works,</p>
  
  <pre><code>echo abcdef | grep -e"def\\|zzz"
  </code></pre>
  
  <p>prints <code>abcdef</code>. Escaping with three backslashes fails,</p>
  
  <pre><code>echo abcdef | grep -e"def\\\|zzz"
  </code></pre>
  
  <p>prints nothing.</p>
  
  <p>Does anyone have an explanation, especially for the 2-backslash case ?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Using this simple argument-printing program, </p>
  
  <pre><code>void main(int argc, char** argv)
  {
      for (int i = 0; i &lt; argc; i++)
          printf("Arg %d: %s\n", i, argv[i]);
  }
  </code></pre>
  
  <p>I investigated what my shell does with the command lines above :</p>
  
  <p><code>-e"def|zzz"</code> becomes <code>-edef|zzz</code></p>
  
  <p><code>-e"def\|zzz"</code> becomes <code>-edef\|zzz</code></p>
  
  <p><code>-e"def\\|zzz"</code> becomes <code>-edef\\|zzz</code></p>
  
  <p><code>-e"def\\\|zzz"</code> becomes <code>-edef\\\|zzz</code></p>
  
  <p>So all double-quotes are removed and the backslashes and pipes are not altered by the shell. I suspect grep itself does something special with the literal string <code>\\|</code>.</p>