linux grep exclude and include

In Linux, you can use grep to both include and exclude patterns in the same search by combining the use of the -e option for including patterns and the -v option for excluding patterns. However, you need to group the include patterns and then pipe the result to grep -v for the exclude pattern.

Here’s how you can do it:

  1. Include one pattern and exclude another:
    Find lines that contain “info” but not “error”:
   grep 'info' filename | grep -v 'error'
  1. Include multiple patterns and exclude one:
    Find lines that contain either “info” or “warning” but not “error”:
   grep 'info\|warning' filename | grep -v 'error'
  1. Include multiple patterns and exclude multiple patterns:
    Find lines that contain either “info” or “warning” but not “error” or “fatal”:
   grep 'info\|warning' filename | grep -v 'error\|fatal'
  1. Include a pattern with line numbers and exclude another:
    Show line numbers for lines that contain “info” but not “error”:
   grep -n 'info' filename | grep -v 'error'
  1. Include a pattern and exclude a pattern using -E for extended regular expressions:
    Find lines that contain “info” but not “error” using extended regular expressions:
   grep -E 'info' filename | grep -v -E 'error'
  1. Include and exclude patterns in a recursive search:
    Find lines in all files within a directory that contain “info” but not “error”:
   grep -r -e 'info' /path/to/directory | grep -v 'error'
  1. Include a pattern and exclude a pattern in a single grep command:
    You can use -e to specify multiple include patterns and -v with -E to specify an exclude pattern:
   grep -E -e 'info' -e 'warning' -- 'error' filename

Here, -- is used to separate the options from the patterns to exclude.

  1. Include a pattern and exclude patterns with specific prefixes:
    Find lines that contain “info” but not lines starting with “error” or “fatal”:
   grep 'info' filename | grep -v '^(error|fatal)'

Remember that when using multiple -e options, grep will match any of the given patterns. The -v option is then used to further filter out the lines that match the exclude patterns. The order of include and exclude matters, especially when the same text string could be both included and excluded.

This entry was posted in File & Directory, Grep Command and tagged , , , , . Bookmark the permalink.