当我使用 grep 命令时,会拾取所有出现的单词,即使它们是其他单词的一部分。例如,如果我使用 grep 来查找单词 'the' 的出现,它也会突出显示 'theatre' 中的 'the'
有没有办法调整 grep 命令,使其只提取完整的单词,而不是单词的一部分?
小智 17
-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)
从 man grep
Geo*_*iou 11
你也可以使用这个:
echo "this is the theater" |grep --color '\bthe\b'
Run Code Online (Sandbox Code Playgroud)
因为一个词与-w 相同。
但是如果你需要搜索多个模式,你可以使用\b,否则如果使用-w,所有模式都将被视为单词。
例如 :
grep -w -e 'the' -e 'lock'
Run Code Online (Sandbox Code Playgroud)
将突出显示和锁定而不是键锁/挂锁等。
使用 \b 您可以区别对待每个 -e 模式。
您可以使用标记\<
(resp. \>
) 测试单词的开头 (resp. end) 是否存在。
因此,
grep "\<the\>" << .
the cinema
a cinema
the theater
a theater
breathe
.
Run Code Online (Sandbox Code Playgroud)
给
the cinema
the theater
Run Code Online (Sandbox Code Playgroud)