How To Exclude Directories with Grep?

The Linux grep command is used to search and filter files and folders for the specified search term or regex pattern. One of the powerful features of the grep command is the ability to search multiple directories recursively. Even though it is a good feature in some cases we may need to exclude some directories for the grep command.

Exclude Directory

A directory can be excluded from the grep command search. The --exclude-dir option is used to specify the directory we want to exclude for the grep match. In the following example, we exclude the directory named backup .

$ grep -R "script" --exclude-dir=backup

Exclude Multiple Directories

We may need to exclude multiple directories for a single grep search. The --exclude-dir can be used multiple times in order to define multiple directories to exclude from a grep match.

$ grep -R "script" --exclude-dir=backup --exclude-dir=abc

Alternatively, we can use the single –exclude-dir option in order to exclude multiple directories. The directory names are provided inside the curly brackets like below.

$ grep -R "script" --exclude-dir={backup,abc}

Exclude Directories with Name Pattern

Directories can be also excluded according to their names by using name patterns. The following wildcard characters can be used for the name pattern definition.

  • ? zero or one occurrence of the previous character.
  • * zero or more occurrence of the previous character.
  • \ is used to quote a wildcard.
$ grep -R "script" --exclude-dir={backup1?,abc2*}
See also  Exact Match with Grep Command

Leave a Comment