I am confused about the backslash character \ and single quotations inside grep. From my understanding it preserves the literal meaning. For example

if I do echo 'This is \., it gives me This is \.

However, if I want to match any actual .(period) I need to use '\.' to escape the special meaning of . in regular expression. For example if a have a file demo.txt taken from example from this website

Problem output

My question is how is the ' ' not preserving the literal value in this case for grep? This is proving to be very confusing for me. Any explanations would be very helpful.


Single quotes protect characters from interpretation by the shell, but grep still treats the argument as a regular expression.

You can turn this behavior off by running grep with the -F or --fixed-strings option:

grep -F 'purchase.' demo.txt

The single quotes are not necessary as none of those p, u, r, c, h, a, s, e or . characters are special to the shell:

grep -F purchase. demo.txt

Or you could use grep without -F but escape the . regular expression operator with \:

grep 'purchase\.' demo.txt

The single quotes are so that \ (which is also special for the shell; a quoting operator there) is passed literally to grep. Or you can use the \ shell quoting operator to quote itself:

grep purchase\\. demo.txt

You can also use the [set] regex operator to match on a literal .:

grep 'purchase[.]' demo.txt

Again, [set] is also a shell operator (a globbing operator there) so needs to be quoted as well (here with single quotes again).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.