How to grep asterisk without escaping?

爷,独闯天下 提交于 2020-02-13 10:25:36

问题


Suppose I have a file abc.txt which contains line ab*cd. When I grep that pattern ab*cd with quotes but without escaping the asterisk it does not work:

> grep ab*c abc.txt 
> grep "ab*c" abc.txt 
> grep 'ab*c' abc.txt 

When I use both quotes and escaping it does work

> grep "ab\*c" abc.txt 
ab*cd
> grep 'ab\*c' abc.txt 
ab*cd

Now I wonder why the quotes do not work and if I can use only quotes without escaping the asterisk.


回答1:


Use the flag -F to search for fixed strings -- instead of regular expressions. From man grep:

   -F, --fixed-strings
          Interpret  PATTERN  as  a  list  of  fixed strings, separated by
          newlines, any of which is to be matched.  (-F  is  specified  by
          POSIX.)

For example:

$ grep -F "ab*c" <<< "ab*c"
ab*c



回答2:


first of all, you should keep in mind: regex =/= glob

* has special meaning in regex. You have to escape it to match it literally. without escaping the *, grep tries to match ab+(any number of b)+c

for example:

abbbbbbbbbbbbc



来源:https://stackoverflow.com/questions/18191548/how-to-grep-asterisk-without-escaping

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