bash 如何在不转义的情况下grep星号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18191548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:13:29  来源:igfitidea点击:

How to grep asterisk without escaping?

bashgrepescaping

提问by Michael

Suppose I have a file abc.txtwhich contains line ab*cd. When I grepthat pattern ab*cdwith quotes but without escaping the asterisk it does not work:

假设我有一个abc.txt包含 line的文件ab*cd。当我使用引号但没有转义星号的grep模式时ab*cd,它不起作用:

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

When I use bothquotes and escaping it doeswork

当我使用这两个引号和逃避它确实工作

> 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 onlyquotes without escaping the asterisk.

现在我想知道为什么引号不起作用,以及我是否可以使用引号而不转义星号。

回答by Rubens

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

使用标志-F来搜索固定字符串——而不是正则表达式。来自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

回答by Kent

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

首先,你应该记住: 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

*在正则表达式中具有特殊意义。你必须逃避它才能真正匹配它。没有转义*,grep 会尝试匹配ab+(any number of b)+c

for example:

例如:

abbbbbbbbbbbbc

abbbbbbbbbbbbc