user2840430
user2840430

Reputation: 3

egrep and grep difference with dollar

I'm having touble understanding the different behaviors of grep end egrep when using \$ in a pattern.

To be more specific:

grep "\$this->db" file   # works

egrep "\$this->db" file  # does not work

egrep "\\$this->db" file # works

Can some one tell me why or link some explanation? Thank you very much.

Upvotes: 0

Views: 202

Answers (2)

EverythingRightPlace
EverythingRightPlace

Reputation: 1197

See man grep:

-E, --extended-regexp
              Interpret PATTERN as an extended regular expression (ERE, see below).  (-E is specified by POSIX.)

If regex are activated (through the usage of egrep) metacharacters like the backslash have to be escaped with a backslash. Therefore the need of \\ to match a literal backslash.

Upvotes: 1

Barmar
Barmar

Reputation: 780869

The backslash is being eaten by the shell's escape processing, so in the first two cases the regexp is just $this->db. The difference is that grep treats a $ that isn't at the end of the regexp as an ordinary character, but egrep treats it as a regular expression that matches the end of the line.

In the last case, the double backslash causes the backslash to be sent to egrep. This escapes the $, so it gets treated as an ordinary character rather than matching the end of the line.

Upvotes: 2

Related Questions