エンジニアを目指す初学者に向けて、わかりやすく解説したブログです。
サイトをリニューアルしました

grepで特定のディレクトリを検索対象から除外する

解決したいこと

grep -rなどでリポジトリの中のキーワードを検索したいが、例えば以下のようなディレクトリは通常検索対象外にしたいはずである。

  • .git
  • node_modules
  • dist

検索のノイズになってしまうため、それを解消する方法を説明する。

# date-fnsを使っている箇所を特定したい
# node_modules配下のファイルも検索に引っかかってしまい、探したいものを探すことができない
$ grep -r 'date-fns'

結論

--exclude-dirオプションを使う。

# 単一のディレクトリを除外する場合
$ grep -r 'date-fns' --exclude-dir=node_modules
./yarn.lock:"date-fns@npm:^4.1.0":
./yarn.lock:  resolution: "date-fns@npm:4.1.0"
./yarn.lock:    date-fns: "npm:^4.1.0"
./package.json:    "date-fns": "^4.1.0",
./src/components/BlogJsonLd.astro:import { formatISO } from 'date-fns'


# 複数のディレクトリを除外する場合
$ grep -r 'date-fns' --exclude-dir={node_modules,.nx,dist}
./yarn.lock:"date-fns@npm:^4.1.0":
./yarn.lock:  resolution: "date-fns@npm:4.1.0"
./yarn.lock:    date-fns: "npm:^4.1.0"
./package.json:    "date-fns": "^4.1.0",
./src/components/BlogJsonLd.astro:import { formatISO } from 'date-fns'