grepが検索時に単語が見つからないのはなぜですか?

grepが検索時に単語が見つからないのはなぜですか?

私は単語の一部を検索しようとしたときにgrepがその一致を見つけることができない状況に何度もありました。完全な単語を検索すると機能します。

たとえば、「mysql_」という単語を含むすべてのファイルを見つける必要があります。データベースを処理するために「mysqli」の代わりに「mysql」を使用するレガシーコードを作業しており、「mysql」を使用するコードがどれくらいになるかを確認したかったからです。

今私のコマンドは

grep -rnw './' -e "mysql_"

または

grep -P -rnw '\bmysql_' .

それでも動作しません。

しかし、次のように入力すると:

grep -rnw './' -e "mysql_query"

もちろん、grepはすべての一致を探します。

私は何が間違っていましたか?

ベストアンサー1

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

正規表現では、下線は「単語」文字です。

mysql_これは単語(たとえばmysql_query)の一部としてのみ発生するため、報告されませgrep -wん。

おすすめ記事