Linux 使用 grep 搜索包含点的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10346816/
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
Using grep to search for a string that has a dot in it
提问by Varun kumar
I am trying to search for a string 0.49
(with dot) using the command
我正在尝试0.49
使用命令搜索字符串(带点)
grep -r "0.49" *
But what happening is that I am also getting unwanted results which contains the string such as 0449
, 0949
etc,. The thing is linux considering dot(.) as any character and bringing out all the results. But I want to get the result only for "0.49".
但是发生的事情是我也得到了不需要的结果,其中包含诸如0449
,之类的字符串0949
。事情是 linux 将 dot(.) 视为任何字符并带出所有结果。但我只想得到“0.49”的结果。
采纳答案by geekosaur
grep
uses regexes; .
means "any character" in a regex. If you want a literal string, use grep -F
, fgrep
, or escape the .
to \.
.
grep
使用正则表达式;.
在正则表达式中表示“任何字符”。如果你想有一个文本字符串,使用grep -F
,fgrep
或逃避.
到\.
。
Don't forget to wrap your string in double quotes. Or else you should use \\.
不要忘记用双引号将字符串括起来。否则你应该使用\\.
So, your command would need to be:
所以,你的命令需要是:
grep -r "0\.49" *
or
或者
grep -r 0\.49 *
or
或者
grep -Fr 0.49 *
回答by Joni
grep -F -r '0.49' *
treats 0.49 as a "fixed" string instead of a regular expression. This makes .
lose its special meaning.
grep -F -r '0.49' *
将 0.49 视为“固定”字符串而不是正则表达式。这使得.
它失去了它的特殊意义。
回答by Kevin Davis
You can escape the dot and other special characters using \
您可以使用 \ 转义点和其他特殊字符
eg. grep -r "0\.49"
例如。grep -r "0\.49"
回答by codaddict
You need to escape the .
as "0\.49"
.
你需要逃避.
as "0\.49"
。
A .
is a regex meta-character to match any character(except newline). To match a literal period, you need to escape it.
A.
是一个正则表达式元字符,用于匹配任何字符(换行符除外)。要匹配文字句点,您需要对其进行转义。
回答by tuxuday
Escape dot. Sample command will be.
逃生点。示例命令将是。
grep '0\.00'
回答by cppcoder
Just escape the .
只是逃避 .
grep -r "0\.49"
grep -r "0\.49"
回答by skan
You can also use "[.]"
您也可以使用“[.]”
grep -r "0[.]49"
回答by Afr
There are so many answers here suggesting to escape the dot with \.
but I have been running into this issue over and over again: \.
gives me the same result as .
这里有这么多的答案,提示逃生用点\.
,但我一直在一遍又一遍地运行到这个问题:\.
给我的结果相同.
However, these two expressions work for me:
但是,这两个表达式对我有用:
$ grep -r 0\.49 *
And:
和:
$ grep -r 0[.]49 *
I'm using a "normal" bash shell on Ubuntu and Archlinux.
我在 Ubuntu 和 Archlinux 上使用“普通”的 bash shell。
回答by smc
You can also search with -- option which basically ignores all the special characters and it won't be interpreted by grep.
您还可以使用 -- 选项进行搜索,该选项基本上会忽略所有特殊字符,并且不会被 grep 解释。
$ cat foo |grep -- "0\.49"