Grep is one of the most powerful command-line utility in Linux. It is used to search for a string in a file and display all the lines that contain that string. There are several ways to search multiple words in a file with grep command, and that’s what we’ll be going over today!
In this tutorial, We will show you how to Search Multiple Words (or Strings/Patterns) in a File using Grep along with several examples!
Basic Syntax
The basic syntax to search multiple words in a file is shown below:
grep "word1\|word2" FILE
Or
grep -E "word1|word2" FILE
Or
egrep "word1|word2" FILE
Or
grep -e "word1" -e "word2" FILE
Create a Sample File
For the purpose of this tutorial, create a sample test.txt file with the following contents:
cat test.txt
Output:
hitesh rajesh mahesh
jayesh mahesh rajesh
hitesh vijay Mahesh
Jayesh rajesh Hitesh
hitesha is clever boy
maheshwari
Seach Multiple Words
In this section, we will show you how to search multiple words in a file with hands-on examples.
Let’s search for pattern hitesh and rajesh in a test.txt file:
grep "hitesh\|rajesh" test.txt
Output:
hitesh rajesh mahesh
jayesh mahesh rajesh
hitesh vijay Mahesh
Jayesh rajesh Hitesh
hitesha is clever boy
Example:
You can use option -w with grep command to search for an exact word:
grep -w "hitesh\|rajesh" test.txt
Output:
hitesh rajesh mahesh
jayesh mahesh rajesh
hitesh vijay Mahesh
Jayesh rajesh Hitesh
Example:
You can use option -i to ignore the case as shown below:
grep -iw "mahesh\|rajesh" test.txt
Output:
hitesh rajesh mahesh
jayesh mahesh rajesh
hitesh vijay Mahesh
Jayesh rajesh Hitesh
Example:
If you use -E option with grep command, you just need to use | to separate multiple patterns:
grep -E "mahesh|vijay" test.txt
Or
egrep "mahesh|vijay" test.txt
Output:
hitesh rajesh mahesh
jayesh mahesh rajesh
hitesh vijay Mahesh
maheshwari
Example:
You can use multiple -e option in a single command to use multiple patterns:
grep -e "hitesh" -e "rajesh" -e "vijay" test.txt
Output:
hitesh rajesh mahesh
jayesh mahesh rajesh
hitesh vijay Mahesh
Jayesh rajesh Hitesh
hitesha is clever boy
Example:
If you want to search all the lines that contain both “hitesh” and “mahesh” in test.txt file(in the same order), run the following command:
grep -iE "hitesh.*mahesh" test.txt
Output:
hitesh rajesh mahesh
hitesh vijay Mahesh
Example:
If you want to search all the lines that contain both “hitesh” and “rajesh” in test.txt file(in any order), run the following command:
grep -iE "hitesh.*rajesh|rajesh.*hitesh" test.txt
Output:
hitesh rajesh mahesh
Jayesh rajesh Hitesh
Example:
Conclusion
In the above tutorial, we’ve learned how to find multiple words in a file using the grep command in Linux.
We hope you’ve learned enough to understand each method we’ve covered above. Feel free to comment below with any questions or comments!