- How To Search Multiple Words / String Pattern Using grep Command on Bash shell
- How do I grep for multiple patterns?
- Grep searching two words in a line
- Examples – How to Grep for Multiple Strings, Patterns or Words
- Grep multiple patterns
- How to find multiple strings in files?
- grep multiple strings using awk
- awk command syntax
- sed command syntax
- Conclusion
- How to Grep for Multiple Strings, Patterns or Words
- How to Grep Multiple Patterns – Syntax
- What is the Difference Between grep, grep -E, and egrep?
- Examples of Using Grep for Multiple Strings, Patterns and Words
- How to Grep Multiple Patterns in a File
- Search for Multiple Exact Matches in a File
- Ignore Case when Using Grep for Multiple Strings
- Show the Count of Multiple Matches in a File
- Grep for Multiple Patterns in a Specific File Type
- Search Recursively for Multiple Patterns in a File
- 3 simple and useful tools to grep multiple strings in Linux
- grep multiple strings — syntax
- Perform case-insensitive grep for multiple patterns
- Print filename along with the grep output
- Grep for multiple exact pattern match in a file or path
- grep multiple string with AND condition
- Exclude multiple patterns with grep
- Search for multiple strings with awk — syntax
- Match multiple patterns with OR condition
- Search for multiple patterns with AND condition
- Exclude multiple patterns with awk
- Match and print multiple strings with sed — syntax
- Case in-sensitive match for multiple strings
- Exclude multiple strings
- Conclusion
- Related Posts
How To Search Multiple Words / String Pattern Using grep Command on Bash shell
H ow do I search multiple strings or words using the grep command? For example I’d like to search word1, word2, word3 and so on within /path/to/file. How do I force grep to search multiple words? How can I grep for multiple patterns on Linux, OS X, FreeBSD, or Unix-like system? What is the command to search multiple words in Linux?
The grep command supports regular expression pattern. We can easily grep two words or string using the grep/egrep command on Linux and Unix-like systems. To search multiple patterns, use the following syntax.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | grep or egrep command on Linux and Unix-like OS |
Est. reading time | 4 minutes |
How do I grep for multiple patterns?
- Use single quotes in the pattern: grep ‘pattern*’ file1 file2
- Next use extended regular expressions: egrep ‘pattern1|pattern2’ *.py
- Finally, try on older Unix shells/oses: grep -e pattern1 -e pattern2 *.pl
- Another option to grep two strings: grep ‘word1 \| word2′ input
Grep searching two words in a line
Here are all other possibilities for grep and egrep command:
grep ‘ word1 \| word2 \| word3 ‘ /path/to/file
### Search all text files ###
grep ‘ word* ‘ *.txt
### Search all python files for ‘wordA’ or ‘wordB’ ###
grep ‘ wordA* ‘\» wordB ‘ *.py
grep -E ‘ word1 | word2 ‘ *.doc
grep -e string1 -e string2 *.pl
egrep » word1 | word2 » *.c
### Show all the lines that do not match given pattern/words/strings ###
grep -v ‘ bar \| foo ‘ /dir1/dir2/file1
egrep -v ‘ pattern1 | pattern2 ‘ /path/to/file
Examples – How to Grep for Multiple Strings, Patterns or Words
In this example, search warning, error, and critical words in a text log file called /var/log/messages, enter:
$ grep ‘warning\|error\|critical’ /var/log/messages
To just match words, add the -w option:
$ grep -w ‘warning\|error\|critical’ /var/log/messages
Use the egrep command and you can skip the above syntax to search three words:
$ egrep -w ‘warning|error|critical’ /var/log/messages
Grep multiple patterns
Sometimes we need to grep multiple patterns with special character such as ‘ — ‘ or ‘ — ‘. For example, search for pattern starting with ‘ —ca ‘ or ‘ —no ‘ words. So if you try the following you will get an error on screen such as “ grep: unrecognized option : —ca|—no “. Let us try an example:
$ acme.sh —help | egrep ‘—ca|—no’
In order to tell grep not to treat ‘ — ‘ as command line option prefix pattern as follows:
$ acme.sh —help | egrep — ‘—ca|—no’
$ virt-sysprep —help | egrep — ‘—(truncate|run)’
All other grep or egrep command option must appear before the final — . For instance pass the -w and —color as follows:
acme.sh —help | egrep —color -w — ‘—ca|—no’
How to find multiple strings in files?
Let us try a few more examples with additional options passed to the grep/egrep:
$ grep -e ‘warning\|error\|critical’ /var/log/messages
I recommend that you pass the -i (ignore case) and —color option as follows too:
$ egrep -wi —color ‘warning|error|critical’ /var/log/messages
Sample outputs:
Fig.01: Linux / Unix egrep Command Search Multiple Words Demo Output
grep multiple strings using awk
Say if you are already using the awk command or sed command command, then there is no need to pipe out to grep and feed data from grep. We can process and gather multiple strings using awk or sed as follows to save CPU cycle:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
awk command syntax
$ awk ‘/ error | critical / failed /’ /var/log/httpd/error_log
## case instive search with *gnu/awk* ##
$ awk ‘BEGIN < IGNORECASE=1 >/ error | critical / failed /’ /var/log/messages
$ awk ‘/word1.*word2/’ input
$ awk ‘/myPattern1/ && /myPattern2/’ /path/to/file
## awk not matching i.e. show all line except HTTP/2.0 logs ##
$ awk ‘!/ HTTP\/2.0 /’ /var/log/nginx/cyberciti.bizerror_log
sed command syntax
$ sed -e ‘/ error /b’ -e ‘/ critcial /b’ -e d /var/log/apache/nixcraft.com_error_log
$ sed ‘/ stringOne /!d; / stringTwo /!d’
/backups/conf.txt
## sed negative (NOT) matching. For example, show all hosts except cbz01-www ##
$ sed -n ‘/ cbz01-www /!p’ /etc/hosts
As you can observe, grep syntax is easy to read and implement. However, I provided awk and sed syntax for your shell scripting needs too.
Conclusion
You learned how to use grep command to locate multiple words or strings in a single go. For more information see our all other grep related tutorials or read grep man page by typing the following man command. Alternatively, you can read it online here:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to Grep for Multiple Strings, Patterns or Words
Home » SysAdmin » How to Grep for Multiple Strings, Patterns or Words
Grep is a powerful utility available by default on UNIX-based systems. The name stands for Global Regular Expression Print.
By using the grep command, you can customize how the tool searches for a pattern or multiple patterns in this case. You can grep multiple strings in different files and directories. The tool prints all lines that contain the words you specify as a search pattern.
In this guide, we will show you how to use grep to search multiple words or string patterns. Follow the examples in this tutorial to learn how to utilize grep most effectively.
- Linux or UNIX-like system
- Access to a terminal or command line
- A user with permissions to access the necessary files and directories
How to Grep Multiple Patterns – Syntax
The basic grep syntax when searching multiple patterns in a file includes using the grep command followed by strings and the name of the file or its path.
The patterns need to be enclosed using single quotes and separated by the pipe symbol. Use the backslash before pipe | for regular expressions.
The latest way to use grep is with the -E option. This option treats the pattern you used as an extended regular expression.
The deprecated version of extended grep is egrep.
Another option is to add multiple separate patterns to the grep command.
To do so, use the -e flag and keep adding the desired number of search patterns:
What is the Difference Between grep, grep -E, and egrep?
The egrep command is an outdated version of extended grep. It does the same function as grep -E .
The difference between grep and extended grep is that extended grep includes meta characters that were added later.
These characters are the parenthesis (), curly brackets <>, and question mark. The pipe character | is also treated as a meta character in extended grep.
Examples of Using Grep for Multiple Strings, Patterns and Words
To make sure you understand how to use grep to search multiple strings, we suggest creating a file with some text on which we are going to try out a couple of different use cases.
In our case, we named the file sample.txt and added a few paragraphs of text. We stored the file in the directory of the test user, that is, in /home/test/sample.txt
How to Grep Multiple Patterns in a File
In the examples below, we will use grep instead of extended grep. Do not forget to use the backslash before the pipe character.
Since grep does not support the pipe symbol as the alternation operator, you need to use the escape character (backslash \) to tell the grep command to treat the pipe differently.
For example, to search for the words extra and value in the sample.txt file use this command:
The output highlights the string you wanted to grep.
If the same file is in another directory, you need to navigate to that directory or use the full path of the file:
To search for more than two words, keep adding them in the same manner.
For example, to search for three words, add the desired string of characters followed by a backslash and pipe:
Let’s see how the above grep command looks when using grep -E , egrep , and grep -e :
We will use grep in further examples, but you can use whichever syntax you prefer.
Search for Multiple Exact Matches in a File
If you want to find exact matches for multiple patterns, pass the -w flag to the grep command.
For example, the output below shows the difference between searching without -w and with it:
As you can see, the results are different. The first command shows all lines with the strings you used.
The second command shows how to grep exact matches for multiple strings. The output prints only the lines that contain the exact words.
Note: Grep offers many functionalities. Learn how to use grep for additional use cases.
Ignore Case when Using Grep for Multiple Strings
To avoid missing something when you search for multiple patterns, use the -i flag to ignore letter case.
For example, we will ignore case with this command:
The output shows how the two commands differ. If you include the -i flag and ignore letter case, the result for multiple matches includes all matches.
This way, you get additional results. If you also add the -w flag to this command, you can narrow down the results even further:
Show the Count of Multiple Matches in a File
Let’s say you are monitoring a log file, and you want to see if the number of warnings or messages increases. You don’t want to see detailed results when a large number of matches return.
For example, to show the count of multiple matches in the bootstrap.log file, enter:
The output prints the number of matches. This way, you can quickly determine if the number of warnings and errors increased.
Grep for Multiple Patterns in a Specific File Type
You can use grep to search multiple strings in a certain type of file only. If you want to monitor log files in one directory or if you want to search through all text files, use an asterisk and the file extension instead of a file name.
For example, to search for warnings and errors through all .log files in the /var/log/ directory, enter:
To better demonstrate how this option works, we will only show the count of matches.
The output shows all the files that grep searched through for the strings you used.
Note: If you get a “Permission denied” message, as we did in the example above, you need sudo privileges. To include all files, use sudo with the grep command. Enter the sudo password, and grep will search through all files.
Search Recursively for Multiple Patterns in a File
The grep command searches only in the current directory when you use the asterisk wildcard.
To include all subdirectories when searching for multiple patterns, add the -R operator to grep:
The output will return results from all files the grep command found in the /var/log/ directory and its subdirectories.
In this tutorial, you learned how to use grep to search multiple words or string patterns in a file. The guide also showed you how to use extended grep.
The examples in this article help you practice how to refine your grep search.
Источник
3 simple and useful tools to grep multiple strings in Linux
Table of Contents
How can I grep multiple strings in single line? Is it possible to grep multiple strings using single command from a file? How to match two or more patterns in single file?
There can be multiple scenarios where you would want to grep for multiple strings in a file. I will try to cover the scenarios which I can think of and based on user’s queries on the web, if you have any additional question, feel free to drop your concern in the comment box of this tutorial.
We will use below tools to cover all these questions:
grep multiple strings — syntax
By default with grep with have -e argument which is used to grep a particular PATTERN . Now this pattern can be a string, regex or any thing. We can add » -e » multiple times with grep so we already have a way with grep to capture multiple strings.
Use -e with grep
Use pipe with escape character
Use pipe without escape character using extended grep ( -E )
As you may have observed in the syntax, we can combine grep with many more inbuilt » args » to enhance the grepping functionality. Now we will use these syntax in different examples with more scenarios
Perform case-insensitive grep for multiple patterns
To perform case-insensitive search we must use » -i or —ignore-case «, from the man page of grep:
In this section we will grep for all the lines containing error , warning and fatal from /var/log/messages , based on the syntax you can use:
Now since we are combining our syntax to grep multiple strings with -i , grep would perform an case in-sensitive search in /var/log/messages file
grep multiple string with case insensitive
Print filename along with the grep output
Now it is possible that you may try to grep for multiple strings in some path for a bunch of files. In such case you may get the matching pattern output with lines, but by default you will NOT get the filename of individual matching PATTERN
To also print the filename with grep use -H or —with-filename argument. From the man page of grep,
So again we will use our grep syntax in combination with -H argument to also print filename along with the matched strings in the respective lines:
Here if you observe, I have added -H with all our existing grep commands to lookout for all the files under /var/log/* containing error , warn , or fatal . There is no particular sequence to be followed while assigning these arguments with grep.
can be also written as
and we will get the same output from all the commands. So as you see we can write the set of arguments in different order, combined or separately with grep so the sequence doesn’t matter as long as you are using the right arguments.
grep multiple strings in all files in a path
Grep for multiple exact pattern match in a file or path
By default when we search for a pattern or a string using grep , then it will print the lines containing matching pattern in all forms.
For example, if you grep for » warn «, then grep will also match » warning «, » ignore-warning » etc. Since all these words contain our string i.e. warn . But if your requirement was to only print the exact word match i.e. » warn » then we must use -w or —word-regexp along with grep . From the man page of grep:
To search for multiple strings with exact word match in /var/log/messages we will use
Following is a snippet from my server
Match exact word with grep
grep multiple string with AND condition
In the earlier examples we were using OR condition to match multiple strings. Now if you have a requirement to search for multiple strings with AND condition i.e. all the provided patterns must match in the same line
For example, I have this file:
I would like to grep for lines having both » success » and » activated «. The easiest way to achieve this is to first grep for the first match and then grep the next string
So we have now lines having both the strings, but the demerit of this method is if you have multiple strings then you will end up using grep multiple times which will not look tidy
Alternatively we can also use grep in this format.
Since we do not know the order of occurrence for both the strings we are grepping both the patterns in both the possible order. This does the job but again can be messy for multiple strings search.
Exclude multiple patterns with grep
We can use grep with -v or —invert-match to invert the selection i.e. to exclude the provided pattern from the match. We can provide multiple strings to the exclusion list. In this example we want to have all the lines except the ones having » sshd » or » activated » in /tmp/somefile
Search for multiple strings with awk — syntax
For most of the straight forward use cases, you can just use grep to match multiple strings or patterns but for complex use cases, we may consider awk as an alternative. The basic syntax to match a single PATTERN with awk would be:
To match multiple patterns:
Match multiple patterns with OR condition
To perform case-insensitive search of a string or pattern we can use below syntax:
For example to grep for all the lines having » Error » or » Warning » in /var/log/messages we can use:
But to perform case-insensitive we will use IGNORECASE in this example:
Following is a snippet from my server:
Search multiple patterns with awk
Search for multiple patterns with AND condition
In the above example, we are searching for pattern with OR condition i.e. if either of the multiple provided strings are found, print the respective matched line. But to print the lines when all the provided PATTERN match, we must use AND operator. The syntax would be:
Now we will use this syntax to search for lines containing » Success » and » activated » in our /tmp/somefile
To perform case-insensitive search we will use below syntax:
Now we use this syntax in our example:
Exclude multiple patterns with awk
We can also exclude certain pre-defined patterns from the search. The general syntax would be:
In this syntax we want to exclude all the three PATTERNS from the search. You can add or remove more patterns in the syntax based on your requirement.
For example, to print all the lines except the ones containing » activated «
Match and print multiple strings with sed — syntax
Ideally we use sed for mostly search a pattern and then perform an action on the search pattern or line such as delete, replace etc. But we can also use sed in some specific scenarios to match a single or multiple pattern and just print the matched content from a file.
The syntax to match and print single pattern would be:
Here we use -n (or you can use —quiet or —silent ) in combination with » p » to print the pattern space i.e. do not print unless a pattern match is found
Similarly the syntax to match multiple strings with OR condition would be:
Alternatively we can also use sed with -e to add multiple scripts (i.e. conditions) to match a pattern in our case.
You can add or remove PATTERN using the provided syntax n no of times based on your requirement
For example, to match » activated » and » reloaded » in our file
Case in-sensitive match for multiple strings
There is no single argument similar to awk or grep in sed to perform case insensitive match for single or multiple patterns. So we must provide the uppercase and lowercase characters of the possible char for which we assume there can be variations.
For example, in my case there is a possibility the file may contain » success » or » Success » with uppercase » S » so I will put this in our example:
So now sed will look for match of » success » with both uppercase and lowercase » S «. So if you feel there can be variations for more characters, then you must use the same method for all such possible options
Exclude multiple strings
We can also exclude multiple strings using NOT( ! ) operator in the above syntax.
For example to print all the lines except the ones having » sshd » and » reload «
Conclusion
In this tutorial we learned about different Linux tools which we can use to grep multiple strings from a file or a path. The most reliable tool in most straight forward cases would be grep but in more complex scenarios we can use sed , awk , gawk etc. You have the flexibility to perform match using case in-sensitive, recursive, excluding and many other scenarios using these tools.
Lastly I hope the steps from the article to grep multiple strings on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Источник