I have a file with variables in it of the form a(i)%b(j)%c where the a, b, and c are always the same, but the indices i and j may be different (including multiple characters). So I've played around with grep to find instances of these variables, but success depends upon whether or not I include quotes around my search string, and I'm trying to understand why there are differences. I started with searching for cases of single-character indices:

(1) grep a\(.\)\%b\(.\)\%c file works as expected

(2) grep 'a\(.\)\%b\(.\)\%c' file no matches

(3) grep "a\(.\)\%b\(.\)\%c" file no matches

Then (to confuse myself even further!), I tried including the possibility of multiple-character indices:

(4) grep a\(.*\)\%b\(.*\)\%c file doesn't work - zsh :no matches found: a(.)%b(.)%c

(5) grep 'a\(.*\)\%b\(.*\)\%c' file works

(6) grep "a\(.*\)\%b\(.*\)\%c" file works

Could someone please explain what's happening in each of these cases? In case (4), it looks like the shell (zsh) is doing something different because of the asterisks, but I'm not sure what it's doing. And why (1), (5), and (6) work but (2) and (3) don't is particularly confusing to me.


  • 1
    As a rule of thumb: always use single quotes with grep unless you really know what you are doing and want shell expansion. In this case I would use: grep 'a([^()]*)%b([^()]*)%c'
    – jimmij
    Nov 14 '14 at 20:03

You must tell apart shell escaping and grep escapes.

Basic regular expressions (BRE; which are used if grep is used without the option -E) treat (, ) and | as normal chars. The sequences \( and \| have special meaning.

Without the quotes the shell treats the backslash as escape character and removes it i.e. grep doesn't see it. With quotes grep sees the backslashes so the meaning of ( and | changes.

With extended regular expressions (grep -E) it is the other way round: ( and | are special and you need a bashslash before them to have them handled as normal characters.

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.