在多个文件中查找包含特殊字符或空格的单词

在多个文件中查找包含特殊字符或空格的单词

如何在目录(包括子目录)内的文件中找到所有精确匹配的单词,这些单词可能被特殊字符或空格或空字符(行首或行尾)包围。我认为这在源代码中搜索时很常见。

假设我想在多个文件中查找单词is。它应该找到以下情况:

is(这是一行中唯一的单词)

(is)

"is"

this is something

例如,grep -r in在其他单词中找到我不需要的匹配项。

答案1

您可以使用-w--word-regexp标志,例如

grep -wr 'is' .

man grep

-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.

相关内容