How can I search for a string with a literal backslash when using grep?

This has to do with what grep sees versus what the shell sees. So, both.

If you want to see what grep sees with various forms of quoting, use, for example:

printf '<%s>\n' G "G" 'G' \G "\G" '\G' \\G "\\G" '\\G'

This will demonstrate what the shell does with the various types of quoting.


If grep sees just a G, it will search for (and highlight, with your settings) just the G matches.

If grep sees a single backslash followed by a G, it will (in your implementation and probably all current implementations) consider that the backslash removes any special meaning from the character G. But there isn't any special meaning to G, so the result will be the same as if you just pass G.

If grep sees two backslashes, the first removes the special meaning from the second. So when grep sees \\G, it searches for a literal backslash followed by a G. That's what you want.

If you use the -F flag to grep, to search for a fixed string, you can pass just \G and get the same result. (That is, if you pass \G so that grep sees \G, which will require that you escape the backslash in some way so the shell doesn't remove it.)

Tags:

Bash

Grep