为什么grep与“ \ <\-v \>”不匹配

时间:2019-05-29 05:17:27

标签: regex bash grep

我想为选项'-v'复制gcc的手册页。

man gcc | grep -w '\-v'有效。但是我想使用正则表达式。

但是,正如我预期的那样,以下行与单词开头的'-v'不匹配:

grep '\<-v' <<<$'-v'

为什么?

1 个答案:

答案 0 :(得分:2)

单词边界转义序列与-w选项和man grep

略有不同
  

-w,--word-regexp

     

仅选择那些包含构成整个单词的匹配项的行。测试是匹配   子字符串必须在该行的开头,或者必须在非单词组成字符之前。   同样,它必须在行的末尾,或后跟非单词组成字符。   单词构成的字符是字母,数字和下划线。

而正则表达式中的单词边界只会在有单词字符的情况下起作用

$ # this fails because there is no word boundary between space and +
$ # assumes \b is supported, like GNU grep
$ echo '2 +3 = 5' | grep '\b+3\b'
$ # this works as -w only ensures that there are no surrounding word characters
$ echo '2 +3 = 5' | grep -w '+3'
2 +3 = 5

$ # doesn't work as , isn't at start of word boundary
$ echo 'hi, 2 one' | grep '\<, 2\>'
$ # won't match as there are word characters before ,
$ echo 'hi, 2 one' | grep -w ', 2'
$ # works as \b matches both edges and , is at end of word after i
$ echo 'hi, 2 one' | grep '\b, 2\b'
hi, 2 one