Master Grep: Search Multiple Patterns Efficiently with One Command
This guide explains how to use the powerful grep command to search for multiple strings simultaneously, covering basic, extended, and Perl-compatible regular expressions, the OR operator syntax, case‑insensitive searches, whole‑word matching, and practical examples for log file analysis.
What is grep?
The grep command is a versatile command‑line utility that scans one or more input files for lines matching a given regular expression and writes the matching lines to standard output.
Supported Regular‑Expression Syntaxes
grepunderstands three regex syntaxes: Basic , Extended , and Perl‑compatible . If no syntax is specified, it defaults to Basic Regular Expressions.
Searching Multiple Patterns with Basic Regex
To match several alternatives, use the OR (alternation) operator |. In Basic mode the pipe must be escaped. Example: $ grep 'pattern1\|pattern2' filename Always enclose the expression in single quotes so the shell does not interpret special characters.
Using Extended Regular Expressions
With the -E (or --extended-regexp) option, grep treats the pattern as an extended regular expression, and the pipe does not need escaping:
$ grep -E 'pattern1|pattern2' fileCase‑Insensitive Searches
By default grep is case‑sensitive. Add -i (or --ignore-case) to ignore case:
$ grep -i 'fatal|error|critical' /var/log/nginx/error.logWhole‑Word Matching
To restrict matches to whole words (or words surrounded by non‑word characters), use -w (or --word-regexp):
$ grep -w 'fatal|error|critical' /var/log/nginx/error.logWord characters include letters, digits, and the underscore; all other characters are treated as non‑word characters.
Practical Example
Search an Nginx error log for the strings fatal , error , and critical :
$ grep 'fatal\|error\|critical' /var/log/nginx/error.logUsing extended regex removes the need for backslashes:
$ grep -E 'fatal|error|critical' /var/log/nginx/error.logConclusion
The grep command is indispensable for locating text in files. Mastering its multiple‑pattern capabilities—basic and extended regex, case‑insensitivity, and whole‑word matching—greatly speeds up log analysis and other text‑processing tasks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
