How to grep multiple words or strings

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)' *

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.
Your name can also be listed here. Write for us as a freelancer.

2 thoughts on “How to grep multiple words or strings

  1. I need to calculate the received packets from .tr file.
    Problem is that one string is necessary for me but some unnecessary events are also counted that are not needed.

    So I want a solution.

    line1: r 0.500000000 _1_ RTR — 0 cbr 210 [0 0 0 0] ——- [1:0 5:0 32 0] [0] 0 0
    line 2: r 0.501408175 _3_ RTR — 0 AODV 48 [0 ffffffff 1 800] ——- [1:255 -1:255 30 0] [0x2 1 1 [5 0] [1 4]] (REQUEST)

    I want only line 1 but as I am searching for ‘^r’ only so both files are counting. Pls help me how can I search the line where 2 patterns are needed?

Leave a comment

Your email address will not be published. Required fields are marked *

Current ye@r *