Terminus
Exclude With Grep

Exclude With Grep

[#excluding-single-pattern]Excluding a single pattern[#excluding-single-pattern]

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

 $ 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 [.inline-code]-w[.inline-code] flag.

 $ grep -v -w "pattern" file

For example:

[#excluding-multiple-patterns]Excluding multiple patterns[#excluding-multiple-patterns]

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

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

For example:

Alternatively, you can use the [.inline-code]-E[.inline-code] flag combined with the [.inline-code]|[.inline-code] symbol:

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

For example:

[#excluding-files-and-directories]Excluding Files and Directories From a Search[#excluding-files-and-directories]

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

[#excluding-files]Excluding files[#excluding-files]

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

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

For example:

[#excluding-directories]Excluding directories[#excluding-directories]

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

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

For example: