How to grep multiple words or strings

Last updated on November 24, 2020 by Dan Nanni

There are cases where you search for files that contain a specific string or term. That is when Linux utilities such as grep or egrep can help. What if you are looking for files that must match more than one string? Here is a quick run down on how you can use grep or egrep to match multiple strings.

To grep for files that contain any of multiple keywords:

$ grep --color -E "word1|word2|word3" *.txt

To grep for files that contain all multiple keywords:

$ grep -l word1 *.txt | xargs grep -l word2 | xargs grep -l word3

To grep for files that contain multiple words (without any order) in one line:

$ grep word1 *.txt | grep word2 | grep word3

To grep for files that contain multiple ordered words in one line:

$ egrep '(word1.*word2.*word3)' *

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean