Sahil
Sahil

Reputation: 9478

What is wrong with 'echo 'a\\b' | grep "\\"'

When I am running this

echo 'a\\b' | grep '\\'

it correctly identifies the backslashes

but when I used the double quotes

echo 'a\\b' | grep "\\"

It is not running and it is returning a trailing backlash error, I can't figure out why that happens. It should work exactly similar to single quotes as I have escaped the backslashes.

Upvotes: 0

Views: 467

Answers (3)

jix
jix

Reputation: 329

There are multiple places where backslash escapes can be processed:

  • In your shell: This happens when you use double quotes and not single quotes. Note that this is a very limited processing and escapes like "\n" will not work. This means when you do echo "a\\b" echo will get a\b as first argument while when you're executing echo 'a\\b' echo will get a\\b as first argument.
  • In the program you're calling: grep will parse the input as POSIX regular expression which has its own set of escapes. echo may or may not handle escape codes by default. My /bin/echo will not process escape codes by default, my bash bulitin echo also won't but my zsh builtin echo will. If a certain behaviour is wanted this can be specified by -e to enable escapes or by -E to disable escapes.

So if you're calling grep "\\" the shell will process the \\ escape sequence and pass \ to grep which will try to parse that as a regular expression and correclty complains about a trailing backslash.

So when you use double quotes you have to double escape everything resulting in the rather clumsy echo 'a\\b' | grep "\\\\".

To get the least amount of escaping you can use echo 'a\\b' | grep '\\' or even echo 'a\\b' | grep -F '\', where the -F flag tells grep to interpret the pattern as verbatim string and not as a regular expression. If you happen to have an echo that processes escapes by default (this will result in echo 'a\\b' printing a\b) you also need to add -E to the echo command.

Upvotes: 3

afflux
afflux

Reputation: 151

grep does a bit of basic regular expression matching.

When in double quotes, the shell parses \\, so \\ will resolve to a single backslash as a parameter.

Additionally, grep does a bit of basic regular expression matching, so to match a single backslash you need to pass two backslashes to grep.

So by calling grep "\\" you actually get grep \, which does not parse as a regular expression, therefore makes grep fail.

To correctly match only double backslashes, do grep -F '\\' (which means fixed string matching instead of regex), grep '\\\\' or grep "\\\\\\\\".

Upvotes: 1

Andrew White
Andrew White

Reputation: 53516

When using double quotes the \\ gets evaluated into \. Single quotes leaves things as-is. Do an echo "\\" to see what I mean.

Upvotes: 4

Related Questions