The grep is the acronym of the Global Regular Expression Print and is a command line tool used to search strings of characters in specific files. The pattern of the searched line is known as a regular expression and when this command is executed it prints the line with the match. This command in Linux is useful for filtering through large files.
Through the grep command, you can search for multiple words in different files. In this tutorial, we will discuss the use of grep for finding multiple files with different operators.
How to grep Multiple Words in Linux
The grep command comes pre-installed in almost all Linux distributions. However, if it is missing you can install it via the following command:
The grep command consists of three parts, first is grep, second is the pattern you need to find and the third is the name of the file or the path of the file. The syntax of the command for searching the pattern with the file name is:
The basic syntax of the grep command for searching the multiple words with the file path is:
Here I am searching multiple words Linux and system in doc1.txt file:
If you are searching the multiple words through the file path the command will be as follows:
How to Use Extended grep for Finding Multiple Words
To search for multiple words in a single file use the -e operator with the file name or file path. The syntax of the command is:
Here I am searching the Linux and System in the doc1.txt file:
How to Find multiple Exact Matches Using grep Command in Linux
To find the multiple exact matches use the -w operator with the grep command. The syntax of the command is:
Ignore Case in the grep Command
The grep commands are case sensitive and to avoid that you can use the -i operator. This will print both upper-case and lower-case matches of the given input patterns.
If you use the -i to search the linux/system in doc1 the command will be as follows:
Count Number of Matches Using grep Command
The grep command can also display the total count of matches it finds in the system file. Use the -c operator with the grep command:
Search the number of counts of the Linux and system words in doc1 via the following command:
How to grep More Than Two Words in Linux
If you want to use the grep command to find the more than two words in Linux, use the following command syntax:
In my case I am using finding the three words Linux, operating and system in my doc1.txt file:
While working in the command line we often use the grep command for searching the words. The grep command is the most useful and powerful command of Linux with different operator and search options. With this command, you can find the specific words, and patterns in the file. Understanding the grep command will save a lot of time for looking at large files.