为什么在搜索单词的一部分时找不到 grep?

Tur*_*lov 0 grep regular-expression

我曾多次遇到过这种情况,当我想搜索单词的一部分时,grep 找不到那些匹配项。当我搜索完整单词时它有效。

例如,我需要查找所有包含“mysql_”字样的文件。因为我正在处理使用“mysql”而不是“mysqli”来处理数据库的遗留代码,并且想看看有多少代码使用“mysql”。

现在,我的命令是

grep -rnw './' -e "mysql_"
Run Code Online (Sandbox Code Playgroud)

或者

grep -P -rnw '\bmysql_' .
Run Code Online (Sandbox Code Playgroud)

这仍然不起作用。

但如果我输入:

grep -rnw './' -e "mysql_query"
Run Code Online (Sandbox Code Playgroud)

当然,grep 会找到所有匹配项。

我究竟做错了什么?

xen*_*oid 5

因为您使用的是 '-w' 参数,这意味着您的搜索模式应该作为一个完整的单词出现(换句话说,是分隔的“非单词”字符):

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

请注意,在正则表达式中,下划线是“单词”字符。

由于mysql_仅作为单词的一部分出现(如mysql_query),因此grep -w不报告它。