问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/19147498/egrep-and-grep-difference-with-dollar