首页 > 解决方案 > 为什么 grep 不匹配 "\<\-v\>"

问题描述

我想在 gcc 的手册页中查找选项“-v”。

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

但是,正如我所料,以下行与单词开头的“-v”不匹配:

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

为什么?

标签: regexbashgrep

解决方案


单词边界转义序列与选项略有不同-w,从man grep

-w, --word-正则表达式

仅选择那些包含构成整个单词的匹配项的行。测试是匹配的子字符串必须在行首,或者前面有一个非单词组成字符。同样,它必须位于行尾或后跟非单词组成字符。构成单词的字符是字母、数字和下划线。

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

$ # 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

推荐阅读