Skip to content
shellhacks.dev
Text Processing

Exclude Directories from a Recursive grep Search

Skip directories in a recursive search with grep --exclude-dir. It matches the directory's name, so a path with a slash in it excludes nothing at all.

1 min read
Summarize in AI

A search through a project returns the same hits again from vendored code and from .git.

Shell
mkdir -p src node_modules/pkg .git
echo needle > src/app.js
echo needle > node_modules/pkg/index.js
echo needle > .git/note
grep -rn needle . | sort
echo ---
grep -rn --exclude-dir=node_modules --exclude-dir=.git needle .
echo ---
grep -rn --exclude-dir=node_modules/pkg needle . | sort
Text
./.git/note:1:needle
./node_modules/pkg/index.js:1:needle
./src/app.js:1:needle
---
./src/app.js:1:needle
---
./.git/note:1:needle
./node_modules/pkg/index.js:1:needle
./src/app.js:1:needle

Each --exclude-dir takes a glob, and grep skips any directory whose name matches while it descends. The GNU grep manual says the pattern is matched against the final component for a directory found while recursing. That explains the last block, where a pattern with a slash in it matches no directory name and every hit comes back. Braces cover several names at once, as in --exclude-dir={.git,node_modules}.

The brace form is expanded by Bash, not by grep, and a plain sh script gets it literally. A command line directory such as . is matched too, so --exclude-dir=. removes the whole search. For a path-based exclusion use find with -path ... -prune, or git grep, which honors .gitignore.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.