linux grep multiple words

In Linux, to use grep to search for multiple words in a file, you can simply separate the words with a space or use them as part of a regular expression. Here are some examples:

  1. Search for lines containing both “error” and “fatal”:
   grep 'error fatal' filename
  1. Search for an exact phrase (case-sensitive):
   grep 'This is the exact phrase' filename
  1. Search for an exact phrase (case-insensitive):
   grep -i 'This is the exact phrase' filename
  1. Search for lines containing any of the words:
   grep 'word1\|word2\|word3' filename

Here, | is used as the OR operator in regular expressions.

  1. Search for multiple patterns using regular expressions:
   grep 'regexp1\|regexp2' filename

You can use more complex regular expressions separated by |.

  1. Search for lines containing “error” but not “info”:
   grep 'error' filename | grep -v 'info'

Or using -v option to invert the match:

   grep 'error.*info' filename
  1. Search for lines containing “error” or “warning” (using extended regular expressions):
   grep 'error\|warning' filename
  1. Use parentheses for grouping in regular expressions:
   grep '(error|warning): [0-9]+' filename

This will match lines with either “error:” or “warning:” followed by a number.

  1. Search for lines with multiple words and print line numbers:
   grep -n 'word1 word2' filename
  1. Search recursively for multiple words in a directory:
   grep -r 'word1\|word2' /path/to/directory
  1. Combine grep with ls to filter filenames and contents:
   ls -l | grep 'word1\|word2'
  1. Use grep with egrep or grep -E for extended regular expressions:
   grep -E 'word1|word2' filename

Remember to use single quotes ' around the pattern to prevent the shell from interpreting the special characters like |. If you want to include a single quote in the pattern, you can use " or escape it with a backslash \. Adjust the regular expressions according to your specific search requirements.

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