egrep and grep difference with dollar

﹥>﹥吖頭↗ 提交于 2021-02-11 17:24:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!