9.9 在文件中只搜索整个词

-w

回想一下在9.6节中,第一次学习使用grep命令。你要搜索pain这个词,而grep命令忠实地返回一列结果,告诉你什么位置使用了pain。

  1. $ grep pain *
  2. fiery inferno in space.txt:watch the paint peel,
  3. three_no_more_forever.txt:all alone and in pain
  4. the speed of morning.txt:of a Chinese painting.
  5. 8 hour a day.txt:nice paint job too
  6. ghost pain.txt:Subject: ghost pain

在默认情况下,grep命令搜索字符串pain所有可能出现的位置,显示包含pain的整行内容,包括paint和painting。如果搜索的文件中包含painless、Spain、或painstaking,包含这些词的行也会显示出来。但如果只需要精确匹配pain的行,又该怎么办呢?这时就要使用-w(或--word-regexp)选项。

  1. $ grep -w pain *
  2. three_no_more_forever.txt:all alone and in pain
  3. ghost pain.txt:Subject: ghost pain

当搜索结果太多时,这个选项确实能够缩小结果范围,可以轻松找出需要的内容。