【发布时间】:2013-10-02 21:55:46
【问题描述】:
在模式中使用 \$ 时,我无法理解 grep end egrep 的不同行为。
更具体:
grep "\$this->db" file # works
egrep "\$this->db" file # does not work
egrep "\\$this->db" file # works
有人可以告诉我原因或链接一些解释吗? 非常感谢。
【问题讨论】:
在模式中使用 \$ 时,我无法理解 grep end egrep 的不同行为。
更具体:
grep "\$this->db" file # works
egrep "\$this->db" file # does not work
egrep "\\$this->db" file # works
有人可以告诉我原因或链接一些解释吗? 非常感谢。
【问题讨论】:
shell 的转义处理正在吃掉反斜杠,因此在前两种情况下,正则表达式只是$this->db。区别在于grep 将不在正则表达式末尾的$ 视为普通字符,而egrep 将其视为匹配行尾的正则表达式。
在最后一种情况下,双反斜杠导致反斜杠被发送到egrep。这会转义 $,因此它被视为普通字符而不是匹配行尾。
【讨论】:
见man grep:
-E, --extended-regexp
Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)
如果正则表达式被激活(通过使用egrep),像反斜杠这样的元字符必须用反斜杠转义。因此需要\\ 来匹配文字反斜杠。
【讨论】: