# grepの基本と応用
# はじめに
Linuxで頻繁に使用するgrepコマンド。この基本的な使い方と、複雑な応用的な使い方を紹介します。
# 基本
grepはファイル内文字列を検索するコマンドです。以下のオプションを付けてよく使用します。
- -r 再帰的に
- -n 行番号を表示
- | grep パイプで受け渡して再度grepすると、and条件で絞り込むのと同じことになる
# 実行例
現在のディレクトリ配下を再帰的に"search_word"という文字列を探し行ナンバーを付けて返す
grep -rn "search_word" ./
# and検索
grep -rn "search_word" ./ | grep "second"
# 応用編 複雑なgrep
-I バイナリファイルを除外する
--include={,,} 該当ファイルを含む
--exclude={,,} 該当ファイルは除く
--exclude-dir={,,} 該当ディレクトリは除く
-v 文字を除く
-e -e -e grepをOR条件で繋ぐ
"\s" 空白文字(正規表現)
# 例1:ファイルやディレクトリを限定して検索
再帰的に、行ナンバーを付けて、バイナリファイルを除いて、var_dump" という文字を探す。
.php .phar .html で終わるファイルを含む条件で。
しかし、test.php と debug.php というファイルは除外する。
更に以下のディレクトリ配下のファイルは除外する。
vendor,node_modules,.git,bin,js,css
grep -rnI "var_dump" . --include={"*.php","*.phar","*.html"} --exclude={test.php,debug.php} --exclude-dir={vendor,node_modules,.git,bin,js,css}
# 例2:AND条件、OR条件の組み合わせ
ファイルやディレクトリを限定して検索後に、
更に grep に-vを付けて該当文字を除く。
そのとき OR条件で複数条件の文字を除く。
結果が多いので result.txt に出力する
grep -rnI "ngword" ./ | grep -v -e "@gmail" -e "file" -e "\*\s" -e "\s//" > result.txt
# 例3:正規表現
- -E 正規表現を使う
""内に正規表現を使って検索している Laravel のクエリ発行箇所を探す grep
grep -rnIE "::select|::all|::find|::findOrFail|::where|::orWhere|::whereIn|::update|::create|::delete|::restore|::forceDelete|::save" . --include={".php",".phar","*.html"} --exclude={cell.php,debug.php} --exclude-dir={vendor,node_modules,.git,bin,js,css}