Website Vidya
Cloud & DevOpsStep-by-Step Guide

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.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
Grep Multiple Patterns: Match Strings, Words, and Regex in Linux
AI Executive SummaryWebsiteVidya AI

10 min read

Learn grep multiple patterns with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What grep Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

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.

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.

Advertisement
Grep Multiple Patterns: Match Strings, Words, and Regex in Linux — syntax, flags, and practical terminal workflow diagram
Grep Multiple Patterns: Match Strings, Words, and Regex in Linux — command syntax, key options, and production workflow reference.

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:

Advertisement

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 / FlagLong Form / ArgumentTechnical Behavior and Purpose
-e--regexp=PATTERNSpecify an individual pattern; can be repeated to match multiple expressions with logical OR.
-E--extended-regexpInterpret pattern as an Extended Regular Expression, enabling unescaped pipe (|) alternation.
-F--fixed-stringsInterpret patterns as fixed literal strings rather than regular expressions (uses Aho-Corasick).
-f--file=FILEObtain patterns from FILE, one per line. Empty pattern lines match all input lines.
-w--word-regexpSelect only those lines containing matches that form whole words for all patterns.
-i--ignore-caseIgnore case distinctions across all specified search patterns.
-v--invert-matchInvert matching: select lines that do NOT match any of the specified patterns.
-c--countPrint 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.

Advertisement

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

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

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Grep natively evaluates multiple patterns with logical OR. To perform a logical AND search, either pipe grep commands together (e.g. grep 'pat1' file | grep 'pat2') or use regular expression lookaheads with Perl-compatible regex: grep -P '(?=.*pat1)(?=.*pat2)' file.
There is no fixed limit imposed by grep; it is limited only by available system memory and the operating system's maximum command-line argument length (ARG_MAX). For more than 20 patterns, using a pattern file with -f is cleaner and avoids command-line length limits.
Yes. When searching for multiple fixed strings without regular expression wildcards, grep -F -f uses the Aho-Corasick algorithm, which scales near-independently of the number of patterns and avoids the compilation overhead of regular expression automata.
Combine the -v (--invert-match) flag with -E and pipe alternation: grep -v -E 'pattern1|pattern2|pattern3' file.txt will discard any line that contains any of the three patterns.
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout