How to use grep to search for a word in a file while excluding certain directories is easy with the “–exclude-directory” option, but even when this option is not available we can still get the same results with some command line magic.
grep
Grep allows us to search a file (or files) for a string in that file.
Search for the word ‘needle’ from the current directory recursively (-r
) through any sub-directories.
grep -i -r 'needle' .
Note: This search is not case-sensitive (i.e. case-insensitive) because we are using -i
). In other words this search will match ‘needle’, ‘NEEDLE’, ‘nEeDLe’, etc.
Exclude a Directory
We can exclude a directory using the --exclude-dir
option.
Search for the word ‘needle’ from the current directory recursively through any sub-directories, while excluding the .git
directory.
grep -i -r --exclude-dir=".git" 'needle' .
Exclude Multiple Directories
Search for the word ‘needle’ from the current directory recursively through any sub-directories, while excluding the .git
, vendor
, and tests
directories.
grep -i -r --exclude-dir="vendor" --exclude-dir=".git" --exclude-dir="tests" 'needle' .
Exclude a Directory without “exclude-dir” option
Unfortunately, you may find older versions of grep that do not support the --exclude-dir
option (and if you’re working on someone else’s server you may not be able to update grep).
In this case, we can exclude a directory by first using find
to list the files and then (with the help of xargs
) running the results of find
through grep
.
Search for the word ‘needle’ from the current directory recursively through any sub-directories, while excluding the .git
directory.
Get a list of the files from the current directory recursively through any sub-directories, while excluding the .git
directory. Then use grep
on the files returned by find
to look for ‘needle’.
find . -type f ! -path "./.git/*" | xargs grep 'needle' -H
Get a list of the files from the current directory recursively through any sub-directories, while excluding the .git
, vendor
, and tests
directories. Then use grep
on the files returned by find
to look for ‘needle’.
find . -type f ! -path "*/.git/*" ! -path "*/vendor/*" ! -path "*/tests/*" | xargs grep 'needle' -H
Note It is important to include the -H
parameter for grep so even if our find commands return only one file, we still display the filename in the results.
Leave a Reply