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
How to grep asterisk without escaping?
提问by Michael
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:
假设我有一个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 -F
to 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