Grep Multiple Patterns: Match Strings, Words, and Regex in Linux
Learn grep multiple patterns with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
10 min read
Learn grep multiple patterns with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What grep Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Searching for grep multiple patterns simultaneously is an essential technique when filtering complex application logs, identifying related telemetry events, or auditing source code for diverse identifiers. Rather than running sequential grep commands or writing cumbersome shell loops, grep allows you to express disjunctions (logical OR), conjunctions (logical AND), and bulk pattern evaluations in a single pass over your data.
To search for multiple patterns using grep in Linux, specify multiple -e options (e.g. grep -e 'error' -e 'warning' file.log) or use Extended Regular Expressions with the pipe delimiter (e.g. grep -E 'error|warning' file.log). To match against a long list of patterns, store them in a text file and load it with grep -f patterns.txt file.log.
In production environments, incident diagnosis rarely involves looking for a single static string. A failing payment service might manifest as 'TimeoutException', 'ConnectionRefused', or 'HTTP 504' across thousands of log lines. By harnessing grep's built-in multi-pattern facilities—including multiple -e flags, Extended Regular Expression (ERE) alternation (|), and pattern files (-f)—you can consolidate diagnostic pipelines into high-speed, deterministic operations.
Understanding the trade-offs between pattern compilation methods, regular expression engines, and memory limits ensures your multi-pattern searches execute efficiently without falling victim to shell quoting pitfalls or excessive CPU utilization on high-throughput log streams.
What grep Does and When to Use It
When evaluating multiple patterns, GNU grep alters its internal matching strategy based on the flags provided. When combining -F (--fixed-strings) with multiple patterns (either via multiple -e options or a newline-delimited file via -f), grep employs the Aho-Corasick string matching algorithm. Aho-Corasick constructs a trie automaton with failure transitions, allowing grep to locate any of thousands of target keywords simultaneously in linear time relative to input length, regardless of pattern count.
Conversely, when using Extended Regular Expressions (-E) with alternation (e.g. pattern1|pattern2), the GNU regex compiler builds a compound Deterministic Finite Automaton (DFA) representing the union of all pattern state machines. While DFA compilation takes slightly longer during initialization, scanning throughput remains near wire-speed. If backreferences or non-deterministic features are introduced, grep falls back to a Non-deterministic Finite Automaton (NFA) with backtracking, which can degrade throughput on pathological inputs.
Under the hood, grep gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -e, -E, -F, -f turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The grep utility is packaged in grep across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether grep is installed and inspect which binary path and version your shell resolves:
type -a grep
grep --version 2>/dev/null || man -f grep
# Illustrative output (reviewed against documentation)
grep is /usr/bin/grep
grep (grep)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y grep
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y grep
# Arch Linux
sudo pacman -S --noconfirm grep
# Alpine Linux
sudo apk add --no-cache grep
Command Syntax, Arguments, and Exit Status Codes
grep [OPTIONS] -e PATTERN1 -e PATTERN2 [FILE...] | grep -E 'PAT1|PAT2' [FILE...]
Linux offers three primary syntax forms for multi-pattern searches: repeated -e flags (grep -e 'pat1' -e 'pat2' file), alternation within Extended Regular Expressions (grep -E 'pat1|pat2' file or egrep 'pat1|pat2' file), and external pattern lists read from disk (grep -f pattern_list.txt file).
Each pattern specified via -e is treated as an independent match criteria evaluated with logical OR semantics: if any pattern matches the current line, that line is emitted to stdout. When combining multiple patterns with -w (--word-regexp), word boundaries are enforced across every specified pattern individually, preventing substring collisions across tokens.
0— One or more of the specified patterns matched at least one line of input.1— None of the specified patterns were found across any evaluated file or stream.2— An error occurred; missing pattern file, invalid regex syntax, or unreadable file.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-e | --regexp=PATTERN | Specify an individual pattern; can be repeated to match multiple expressions with logical OR. |
-E | --extended-regexp | Interpret pattern as an Extended Regular Expression, enabling unescaped pipe (|) alternation. |
-F | --fixed-strings | Interpret patterns as fixed literal strings rather than regular expressions (uses Aho-Corasick). |
-f | --file=FILE | Obtain patterns from FILE, one per line. Empty pattern lines match all input lines. |
-w | --word-regexp | Select only those lines containing matches that form whole words for all patterns. |
-i | --ignore-case | Ignore case distinctions across all specified search patterns. |
-v | --invert-match | Invert matching: select lines that do NOT match any of the specified patterns. |
-c | --count | Print only the aggregate count of lines matching any of the specified patterns. |
The choice between grep -E 'p1|p2|p3' and grep -F -f patterns.txt depends primarily on pattern volume and volatility. For small sets of 2 to 5 search terms, grep -E with quoted pipe characters is the most readable and compact syntax for interactive terminal usage.
For large sets containing dozens or hundreds of indicators of compromise (IOCs), IP addresses, or package names, storing search terms in a file and using grep -F -f terms.txt is vastly superior. The -F flag triggers the high-performance Aho-Corasick algorithm, bypassing regex compilation entirely and preventing special characters like dots, brackets, and slashes from causing syntax errors.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Match Multiple Strings Using Repeated -e Options
Search system logs for lines containing either 'error', 'failed', or 'critical' using multiple -e flags.
grep -i -e "error" -e "failed" -e "critical" /var/log/syslog | tail -n 4
# Illustrative output (reviewed against documentation)
2026-10-22 14:02:11 host systemd[1]: Failed to start Daily apt download activities.
2026-10-22 14:05:30 host kernel: [drm:radeon_pci_probe] *ERROR* radeon kernel modesetting for R600
2026-10-22 14:10:02 host cron[819]: (CRON) error (can't fork)
2026-10-22 14:12:44 host sshd[18412]: Failed password for invalid user admin from 198.51.100.4
Using -e allows specifying distinct pattern targets without needing to escape special regex characters.
2. Match Multiple Patterns with Extended Regex Alternation
Use grep -E with pipe (|) alternation to match multiple HTTP status codes in access logs.
grep -E 'HTTP/1.[10]" (404|500|502|503)' /var/log/nginx/access.log | head -n 3
# Illustrative output (reviewed against documentation)
198.51.100.22 - - [22/Oct/2026:14:01:10 +0000] "GET /api/v1/users HTTP/1.1" 500 241 "-" "curl/7.81.0"
203.0.113.88 - - [22/Oct/2026:14:01:12 +0000] "POST /checkout HTTP/1.1" 502 582 "-" "Mozilla/5.0"
192.0.2.14 - - [22/Oct/2026:14:01:15 +0000] "GET /missing.html HTTP/1.1" 404 162 "-" "curl/7.81.0"
The (404|500|502|503) grouping allows matching any of the specified server error or missing page responses.
3. Read Multiple Search Terms from an External Pattern File
Search user account database for multiple specific login names listed in a text file.
cat << 'EOF' > targets.txt
root
postgres
nginx
nobody
EOF
grep -F -f targets.txt /etc/passwd
# Illustrative output (reviewed against documentation)
root:x:0:0:root:/root:/bin/bash
postgres:x:114:120:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
nginx:x:115:121:nginx user,,,:/nonexistent:/bin/false
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
Passing -f targets.txt instructs grep to load each line of targets.txt as an independent fixed string to match.
4. Simulate Logical AND Matching Using Piped Grep Commands
Find lines in authentication logs that contain BOTH 'sshd' AND 'Failed password'.
grep "sshd" /var/log/auth.log | grep "Failed password" | head -n 2
# Illustrative output (reviewed against documentation)
Oct 22 14:10:02 prod-node sshd[22019]: Failed password for root from 198.51.100.12 port 58291 ssh2
Oct 22 14:10:05 prod-node sshd[22019]: Failed password for root from 198.51.100.12 port 58291 ssh2
While individual grep invocations evaluate patterns with logical OR, piping standard output from one grep into another enforces logical AND.
5. Enforce Whole-Word Matching Across Multiple Keywords
Search source code for variable names 'id', 'name', or 'key' without matching substrings like 'identity'.
grep -w -E 'id|name|key' /opt/app/schema.sql
# Illustrative output (reviewed against documentation)
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
key VARCHAR(64) UNIQUE
);
The -w flag constrains each pattern in the alternation to full word boundaries, rejecting 'userId' or 'apiKey'.
6. Invert Multiple Patterns to Exclude Multiple Noisy Log Categories
Omit both health checks and static asset requests when streaming web server logs.
grep -v -E '(/healthz|/favicon.ico|/robots.txt)' /var/log/nginx/access.log | head -n 3
# Illustrative output (reviewed against documentation)
198.51.100.22 - - [22/Oct/2026:14:20:00 +0000] "POST /api/v2/charge HTTP/1.1" 200 120 "-" "App/1.0"
203.0.113.10 - - [22/Oct/2026:14:20:01 +0000] "GET /dashboard HTTP/1.1" 200 4892 "-" "Mozilla/5.0"
192.0.2.89 - - [22/Oct/2026:14:20:02 +0000] "GET /profile HTTP/1.1" 200 1920 "-" "Mozilla/5.0"
Combining -v with regex alternation discards lines that match any of the excluded path patterns.
Real-World Workflows, Pipelines, and Shell Automation
Log Triage Pipeline: Isolating Critical Web Application Exceptions
Filter multi-gigabyte production application logs for critical exceptions while omitting routine informational events.
#!/usr/bin/env bash
set -euo pipefail
LOG_PATH="/var/log/application/app.log"
PATTERNS="DatabaseConnectionException|OutOfMemoryError|DeadlockDetected|NullPointerException"
echo "=== Triage: Critical Application Exceptions Detected ==="
grep -n -E "$PATTERNS" "$LOG_PATH" \
| grep -v "test-harness" \
| head -n 5 || echo "No critical exceptions found."
# Illustrative output (reviewed against documentation)
=== Triage: Critical Application Exceptions Detected ===
1842:2026-10-22 14:15:01 [CRITICAL] DatabaseConnectionException: Failed to acquire pool lease after 30000ms
1994:2026-10-22 14:15:10 [CRITICAL] DeadlockDetected: Transaction 88219 deadlocked with 88220
2005:2026-10-22 14:15:12 [ERROR] NullPointerException: Session cache token pointer was null
This workflow combines multi-pattern regex alternation with inverted secondary filtering (-v) and line numbering (-n) to rapidly isolate critical production incidents.
Compliance Audit: Scanning Codebases for Blocklisted Security APIs
Audit source code repository for deprecated and insecure cryptographic algorithms loaded from a compliance file.
#!/usr/bin/env bash
set -euo pipefail
cat << 'EOF' > /tmp/banned_crypto.txt
MD5
SHA1
DES_ede3_cbc
RC4
ssl.PROTOCOL_SSLv23
EOF
echo "Auditing /var/www/project for deprecated cryptographic calls..."
VIOLATIONS=$(grep -rnw -F -f /tmp/banned_crypto.txt /var/www/project/src/ 2>/dev/null || true)
if [ -n "$VIOLATIONS" ]; then
echo "[ALERT] Insecure crypto primitives detected:"
echo "$VIOLATIONS"
rm -f /tmp/banned_crypto.txt
exit 1
else
echo "[CLEAN] No banned cryptographic primitives found."
rm -f /tmp/banned_crypto.txt
fi
# Illustrative output (reviewed against documentation)
Auditing /var/www/project for deprecated cryptographic calls...
[CLEAN] No banned cryptographic primitives found.
Using grep -rnw -F -f ensures exact whole-word matching against a bulk security rule file across recursive directories.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding grep inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Be careful when using pattern files (-f) containing trailing blank lines. In POSIX grep, an empty pattern line matches every line of input, which will cause grep to return the entire content of all evaluated files.
When loading patterns from files (-f) or accepting search expressions from users, ensure the pattern file has strict read-only permissions (chmod 600 or 644) and is owned by root. An attacker who can write to your pattern file can inject an empty line or wildcards to exfiltrate unauthorized data or cause denial of service.
Be cautious when constructing complex regular expressions with multiple alternations and wildcard quantifiers (e.g. (a|aa)*b). When evaluating untrusted text inputs, complex nested alternations can trigger exponential backtracking in non-DFA engines, leading to high CPU starvation.
GNU/Linux, BSD, and BusyBox Implementation Differences
In standard POSIX grep (Basic Regular Expressions), the pipe character (|) is treated as a literal character unless escaped with a backslash (\|). However, portability varies across legacy Unix implementations. For reliable portability across GNU, BSD, and BusyBox systems, always pass -E or use egrep when using pipe alternation.
The -e option is fully standardized in POSIX.2 and is safe to use across all Unix platforms, including Solaris, AIX, macOS, and Alpine Linux BusyBox. However, supporting thousands of patterns via -f is significantly faster in GNU grep due to its internal Aho-Corasick implementation compared to older BSD grep versions.
Troubleshooting Common Errors and Diagnostics
Pipe character '|' matching literally instead of acting as OR
Root Cause: The search command was invoked without -E or -P, meaning grep is interpreting the pattern as a Basic Regular Expression (BRE) where | is a literal character.
Resolution: Add the -E flag to enable Extended Regular Expressions, or escape the pipe character with a backslash (\|) in BRE.
# Incorrect (searches for literal 'cat|dog'):
grep "cat|dog" animals.txt
# Correct:
grep -E "cat|dog" animals.txt
# Or using BRE:
grep "cat\|dog" animals.txt
Grep matching every line when using -f pattern file
Root Cause: The pattern file contains an empty line (often at the end of the file created by text editors). In grep, an empty pattern matches everything.
Resolution: Strip empty lines and carriage returns from the pattern file before running grep.
sed -i '/^[[:space:]]*$/d' patterns.txt
grep -f patterns.txt data.log
Quoting errors when embedding bash variables in alternation
Root Cause: Wrapping the pattern string in single quotes prevents the shell from expanding bash variables containing the search strings.
Resolution: Use double quotes so the shell expands variables while preserving regex pipes.
PAT1="error"
PAT2="warning"
grep -E "$PAT1|$PAT2" /var/log/syslog
Alternatives, Related Commands, and Related Tutorials
- Grep Command in Linux: Search Text, Files, and Directories — Practical syntax, flags, and examples for
grep. - Grep Exclude: Exclude Files, Directories, and Patterns in Linux — Practical syntax, flags, and examples for
grep. - ripgrep Command in Linux: Fast Recursive Search with rg — Practical syntax, flags, and examples for
rg. - awk Command in Linux: Syntax, Text Patterns, and Field Processing — Practical syntax, flags, and examples for
awk. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides





Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!