The Great Escape

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.

4 Responses to “The Great Escape”

  1. January 23rd, 2008 | 8:49 pm

    Eww nasty :)

    grep -F “\’” *

  2. January 23rd, 2008 | 9:48 pm

    Bah! :-)

    So that’s what -F does. ;-)

  3. Kess
    April 8th, 2009 | 5:58 pm

    Thank you!

    This has been driving me mad, totally nuts, absolutely crazy. At long last I will be able to rest, be at peace, have some piece.

    Please, accept my undying gratitude for at least an hour or so.

    (And I have to look up that -F flag.)

  4. January 4th, 2011 | 9:09 am

    Thanks! Just what I was looking for!