如何告诉grep匹配每个单词开头的特殊字符

use*_*539 4 grep quoting regular-expression

我有一些关于grep.

  1. 为什么下面的命令匹配' <Hello'?

    $ grep -E "\<H" test
    Hello World
    <Hello
    H<ello
    
    Run Code Online (Sandbox Code Playgroud)
  2. <Hello只匹配“ ”需要做什么?

Lek*_*eyn 6

要防止grep特别解释字符串(正则表达式),请使用-F(或--fixed-string):

$ cat test
one < two
Hello World
X<H
A <H A
I said: <Hello>
$ grep -F '<H' test
X<H
A <H A
I said: <Hello>
Run Code Online (Sandbox Code Playgroud)

请记住正确引用搜索模式,否则您的 shell 可能会对其进行错误解释。例如,如果您grep -F <H test改为运行,shell 将尝试打开一个名为“H”的文件并使用它来提供grep. grep将在该流中搜索字符串“test”。下面的命令大致等价,但不等价于上面的:

 grep -F <H test
 grep -F test <H         # location of `<H` does not matter
 grep -F H test
 cat H | grep -F test    # useless cat award
Run Code Online (Sandbox Code Playgroud)

至于仅匹配单词,请查看手册页grep(1)

   -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.
Run Code Online (Sandbox Code Playgroud)

示例用法(使用上面的测试文件):

$ grep -F -w '<H' test
A <H A
Run Code Online (Sandbox Code Playgroud)

-F这里是可选的,因为<H没有特殊含义,但是如果您打算扩展此文字模式,那么它可能很有用)

要匹配单词的开头,您确实需要正则表达式:

$ grep -w '<H.*' test    # match words starting with `<H` followed by anything
A <H A
I said: <Hello>
Run Code Online (Sandbox Code Playgroud)