Linux 如果字符串中有点,如何搜索确切的单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15521649/
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-08-06 22:29:36  来源:igfitidea点击:

How to grep for the exact word if the string has got dot in it

linuxbash

提问by Pawan

I was trying to search for a particular word BML.Iin a current directory.

我试图BML.I在当前目录中搜索特定单词。

When I tried with the below command:

当我尝试使用以下命令时:

grep -l  "BML.I" *

It is displaying all the results if it contains the word BML

如果包含单词,则显示所有结果 BML

Is it possible to grep for the exact match BML.I

是否可以grep进行精确匹配 BML.I

采纳答案by Brian Agnew

You need to escape the . (period) since by default it matches against any character, and specify -w to match a specific word e.g.

你需要逃离 . (句号)因为默认情况下它匹配任何字符,并指定 -w 以匹配特定单词,例如

grep -w -l "BML\.I" *

Note there are two levels of escaping in the above. The quotes ensure that the shell passes BML\.Ito grep. The \then escapes the period for grep. If you omit the quotes, then the shell interprets the \as an escape for the period (and would simply pass the unescaped period to grep)

请注意,上面有两个级别的转义。引号确保 shell 传递BML\.I给 grep。在\随后逃逸期间grep。如果省略引号,则 shell 会将 the 解释\为该句点的转义符(并将简单地将未转义句号传递给grep

回答by Kent

try grep -wF

尝试 grep -wF

from man page:

从手册页:

 -w, --word-regexp
                  Select  only  those  lines containing matches that form whole words.  The
                  test is that the matching substring must either be at  the  beginning  of
                  the line, or preceded by a non-word constituent character.  Similarly, it
                  must be either at  the  end  of  the  line  or  followed  by  a  non-word
                  constituent  character.  Word-constituent characters are letters, digits,
                  and the underscore.



 -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.)

回答by Bryan Oakley

I use fgrep, which is the same as grep -F

我使用fgrep,这与grep -F

回答by Tharun Ravikumar

Use this command:

使用这个命令:

ls | grep -x "BML.I"

ls | grep -x "BML.I"