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.
$ grep -v "pattern" file
Run in Warp
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.
$ grep -v -w "pattern" file
Run in Warp
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.
$ grep -v -e "fist_pattern" -e "second_pattern" file
Run in Warp
For example:
Alternatively, you can use the -E flag combined with the | symbol:
$ grep -v -E "fist_pattern|second_pattern" file
Run in Warp
For example:
Excluding Files and Directories From a Search
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.
$ grep -r --exclude="expression" "pattern" directory
Run in Warp
For example:
Excluding directories
To exclude one or more directories that match a glob pattern, you can use the --exclude-dir flag.
$ grep -r --exclude-dir="expression" "pattern" directory
Run in Warp
For example:
Written by
Razvan Ludosanu
Founder, learnbackend.dev
Filed Under
Related Articles
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.
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.
How to Make Grep Case Insensitive
By default, grep is case sensitive
Grep Across Multiple Lines
Guide on several cases of using grep across multiple lines
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 Count
Efficiently count lines or occurrences in a file.