Sometimes while using grep command to recursively search for strings in directories & folders, you may need to exclude certain directory & files. You can easily do this using –exclude-directory option. Here is how to exclude directory & files in grep command.
Grep Exclude Directory & Files
Sometimes while using grep with -r or -R option (recursive search) you may need to exclude specific directories from search results. Here is the syntax to exclude files & directories in grep command.
grep -R --exclude-dir=/path/to/dir search_string folder_path
In the above command, you need to specify path to excluded folder or directory in place of /path/to/dir. Remember that this path is relative to the search directory. Next, you need to enter search string, and finally the folder path in which you want to search the specified string.
Here is an example to search string total in folder /home/data but exclude /home/data/old subfolder.
$ sudo grep -R --exclude-dir=old "total" /home/data
Please note, we have specified only old above instead of /home/data/old since you need to specify the excluded directory’s path relative to the search folder.
If you want to exclude multiple folder, enclose their relative paths in a comma-separated manner within curly braces {…}. Here is an example to exclude /home/data/old, /home/data/archive and /home/data/outdated in the above command.
$ sudo grep -R --exclude-dir={old,archive,outdated} "total" /home/data
If you want to exclude files then you can do so using –exclude option. Here is an example to exclude file file.txt from out search.
$ sudo grep -R --exclude=file.txt "total" /home/data
You may also use wildcard characters in –exclude to exclude all .txt and .doc files from search.
$ sudo grep -R --exclude=*.{txt,doc} "total" /home/data
You may also use –exclude and –exclude-dir options together. in grep as shown below.
$ sudo grep -R --exclude=*.{txt,doc} --exclude-dir={old,archive,outdated} "total" /home/data
Also read:
How to Exclude Word Pattern in Grep
How to Install Fail2ban in CentOS 7
How to Copy File to Multiple Directories in Linux
Shell Script to Loop Through Files in Directory
How to Loop Over Lines of File in Bash
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.