Today I wanted to search a large number of text files for a particular sequence of characters. Naturally the tool to use for such a job is grep, as any phule kno.
Unfortunately, the text I wanted to search for was \' — that’s a backslash followed by a single quote. This is mildly problematic because each of these characters has special meanings either for grep or the shell or both.
Long story short, this is what I need to type:
grep \\\\\' *
That’s five backslashes followed by a quote. :-)
WTF? Well: grep uses \\ (two backslashes) to match a single slash, but so does the shell (zsh in this case) so if I entergrep \\' *, the shell would interpret the \\ as meaning “one backslash please” and pass just that one to grep. Unfortunately grep would interpret the backslash as escaping the following character, rather than a literal backslash. Thus, in order to actually give grep the two backslashes it needs in order to match one, I have to type four. Then we also need \' to match the quote character, because a quote on its own is interpreted by the shell as, well, a quote (ie starting a string) — so this final backslash is eaten by the shell in order to pass that quote to grep directly. grep doesn’t treat the quote specially of itself, so finally we have what we want. Sweet.
You have got to love the command line.