9.9 在文件中只搜索整个词
-w
回想一下在9.6节中,第一次学习使用grep
命令。你要搜索pain这个词,而grep
命令忠实地返回一列结果,告诉你什么位置使用了pain。
$ grep pain *
fiery inferno in space.txt:watch the paint peel,
three_no_more_forever.txt:all alone and in pain
the speed of morning.txt:of a Chinese painting.
8 hour a day.txt:nice paint job too
ghost pain.txt:Subject: ghost pain
在默认情况下,grep
命令搜索字符串pain
所有可能出现的位置,显示包含pain的整行内容,包括paint和painting。如果搜索的文件中包含painless、Spain、或painstaking,包含这些词的行也会显示出来。但如果只需要精确匹配pain的行,又该怎么办呢?这时就要使用-w
(或--word-regexp
)选项。
$ grep -w pain *
three_no_more_forever.txt:all alone and in pain
ghost pain.txt:Subject: ghost pain
当搜索结果太多时,这个选项确实能够缩小结果范围,可以轻松找出需要的内容。