Exclude With Grep

Razvan Ludosanu
Razvan LudosanuFounder, learnbackend.dev
Published: December 1, 2023

Excluding a single pattern

When using the grep command, to invert the search and return lines that do not include a specific pattern or exclude a specific string, you can use the -v flag.

Bash
$ grep -v "pattern" file

For example, to search for all lines in a file that do not contain the word "apple", you can use the following command:

Alternatively, if you want to return lines that do not include a specific pattern as a whole, which means a pattern surrounded by non-word characters, such as spaces, punctuation, or the start/end of a line, you can use the -w flag.

Bash
$ grep -v -w "pattern" file

For example:

Excluding multiple patterns

To return lines that specifically do not include multiple patterns (see grep multiple strings for the opposite), you can use the -e flag combined with the -v flag.

Bash
$ grep -v -e "fist_pattern" -e "second_pattern" file

For example:

Alternatively, you can use the -E flag combined with the | symbol:

Bash
$ grep -v -E "fist_pattern|second_pattern" file

For example:

As the opposite of including specific directories in a grep, It is sometimes necessary to exclude certain files and directories from a search when using the recursive flag -r flag.

Excluding files

To exclude one or more files that match a glob pattern, you can use the --exclude flag.

Bash
$ grep -r --exclude="expression" "pattern" directory

For example:

Excluding directories

To exclude one or more directories that match a glob pattern, you can use the --exclude-dir flag.

Bash
$ grep -r --exclude-dir="expression" "pattern" directory

For example:

Written by
Razvan Ludosanu
Razvan LudosanuFounder, learnbackend.dev
Filed under

Related articles


Grep Count

Efficiently count lines or occurrences in a file.

Grep Across Multiple Lines

Guide on several cases of using grep across multiple lines

How to Make Grep Case Insensitive

By default, grep is case sensitive

How To Filter The Output of Commands

Learn how to filter and format the output of commands and logs using the grep, awk, uniq, head, and tail commands.

Grep In a Directory

Learn how to use grep to search for words and phrases within a directory and all its subdirectories, a specific directory, all files, and other variations.

Grep Multiple Strings

How to filter lines and extract specific information from the output of commands or text files based on string patterns and regular expressions with grep.