40+ grep Pattern Matching Examples in Linux (Regex, OR, Pattern File)

40+ grep Pattern Matching Examples in Linux (Regex, OR, Pattern File)

The grep command in Linux is used to search for text patterns inside files or command output. It scans each line of a file and prints the lines that match the specified pattern.

A pattern in grep can be:

  • a simple word or phrase
  • a regular expression (regex)
  • multiple patterns combined with logical conditions

For example, the following command searches for the word error inside a log file.

bash
grep "error" logfile.txt

In this guide, we will explore practical grep pattern matching scenarios including regex patterns, OR conditions, pattern files, and real-world log analysis examples.


Understanding grep Pattern Matching

A pattern in grep is the string or regular expression used to search within files. Grep evaluates each line and prints the lines that match the given pattern.

Grep supports three main pattern types.

Pattern TypeDescriptionExample
Simple text patternSearches exact stringgrep error file.log
Regular expressionSearches using regex rulesgrep '[0-9]' file.txt
Fixed string searchTreats pattern as literal textgrep -F 'a.b' file.txt

Different options allow grep to use different pattern engines.

OptionPattern Type
default grepBasic regular expressions
-EExtended regular expressions
-PPerl compatible regex
-FFixed string search

grep Pattern Matching Quick Reference

The following table provides quick examples of commonly used grep pattern scenarios.

ScenarioExample Command
Search a simple text patterngrep "error" logfile.txt
Ignore case while searchinggrep -i "error" logfile.txt
Match whole word onlygrep -w "error" logfile.txt
Print only matching patterngrep -o "[0-9]*" file.txt
Search multiple patterns (OR)grep -E "error
Search patterns using multiple -e optionsgrep -e error -e warning logfile.txt
Read patterns from filegrep -f patterns.txt logfile.txt
Print line numbers with matchgrep -n "error" logfile.txt
Print lines after matchgrep -A 3 "error" logfile.txt
Print lines before matchgrep -B 3 "error" logfile.txt
Print lines before and after matchgrep -C 3 "error" logfile.txt
Recursive search in directoriesgrep -r "error" /var/log
Search fixed string patterngrep -F "a.b" file.txt
Use extended regexgrep -E "[0-9]{3}" file.txt
Use Perl compatible regexgrep -P "\d+" file.txt

Basic grep Pattern Examples

search for a text pattern in a file

The most basic use of grep is searching for a specific word or phrase in a file. Grep scans the file line by line and prints the lines that contain the matching pattern.

Example:

bash
grep "error" logfile.txt

This command searches for the word error inside logfile.txt and prints all matching lines.

You can also search command output using pipes:

bash
dmesg | grep "usb"

find multiple occurrences of a word

Grep automatically prints every line that contains the pattern. If the pattern appears multiple times in the file, all matching lines will be displayed.

Example:

bash
grep "warning" system.log

If the word warning appears in several lines, grep prints all those lines.

To count how many matches exist, you can combine it with the -c option:

bash
grep -c "warning" system.log

match only whole words

Sometimes a pattern may match partial words. For example, searching for log may also match login or logout.

To match only the exact word, use the -w option.

Example:

bash
grep -w "error" logfile.txt

This ensures only the complete word error is matched.

By default, grep prints the entire line that contains a match. The -o option prints only the matching portion.

Example:

bash
grep -o "[0-9]*" numbers.txt

This extracts only numeric values from the file.

Example output:

bash
42
105
678

search patterns ignoring case

By default grep is case sensitive. The -i option allows case-insensitive searching.

Example:

bash
grep -i "error" logfile.txt

This matches:

  • error
  • Error
  • ERROR

This is useful when searching logs where case may vary.

The -n option prints the line number along with the matching line.

Example:

bash
grep -n "failed" auth.log

Example output:

bash
23:Failed password for root
45:Failed password for admin

This helps identify where the match occurs inside the file.

search patterns recursively in directories

To search for a pattern in multiple files across directories, use the -r or --recursive option.

Example:

bash
grep -r "database" /etc/

This searches every file under /etc for the word database.

You can also restrict the search to specific file types:

bash
grep -r "error" --include="*.log" /var/log

grep Regex Examples & Advanced Patterns

match numeric patterns using regex

To match numbers in a file, you can use a character class.

Example:

bash
grep "[0-9]" file.txt

This finds lines containing at least one digit.

To match sequences of numbers:

bash
grep "[0-9]\+" file.txt

match alphabetic strings

To search lines that contain alphabetic characters only, use a letter range.

Example:

bash
grep "^[a-zA-Z]*$" file.txt

This matches lines containing only letters.

match lines starting with specific characters

The caret ^ represents the start of a line.

Example:

bash
grep "^Error" logfile.txt

This finds lines that start with the word Error.

Example output:

bash
Error connecting to database
Error reading configuration

match lines starting with specific characters

The dollar sign $ represents the end of a line.

Example:

bash
grep "failed$" logfile.txt

This prints lines that end with the word failed.

match strings with exact character length

You can match strings with specific lengths using repetition patterns.

Example: match words with exactly 5 characters.

bash
grep "\b[a-zA-Z]\{5\}\b" file.txt

This matches words containing exactly five letters.

match alphanumeric patterns

To match alphanumeric patterns, combine character classes.

Example:

bash
grep "[a-zA-Z][0-9]" file.txt

This finds patterns where letters are followed by numbers.

Example matches:

bash
user1
id2

extract structured text using regex

You can extract structured patterns such as email addresses.

Example:

bash
grep -o "[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]*" file.txt

This prints only the email addresses found in the file.

extract IP addresses from text

You can use regex to extract IPv4 addresses.

Example:

bash
grep -E "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.log

Example output:

bash
192.168.1.10
10.0.0.5
172.16.0.22

This technique is commonly used for log analysis.


Searching Multiple Patterns

grep pattern1 OR pattern2 using -E

The -E option enables extended regular expressions, allowing OR conditions.

Example:

bash
grep -E "error|warning" logfile.txt

This prints lines containing either error or warning.

search multiple patterns using -e option

You can specify multiple patterns using the -e option.

Example:

bash
grep -e error -e warning -e critical logfile.txt

This searches for all three patterns.

match multiple patterns using regex pipe operator

The pipe operator | can also be used to combine patterns.

Example:

bash
grep -E "failed|denied|invalid" auth.log

This is commonly used when analyzing authentication logs.

match lines containing two patterns (AND condition)

To match lines that contain multiple patterns, use a lookahead regex.

Example:

bash
grep -P "(?=.*error)(?=.*database)" logfile.txt

This prints lines containing both error and database.

search patterns from multiple files

You can search multiple files in one command.

Example:

bash
grep "timeout" file1.log file2.log file3.log

Grep prints matches along with the filename.

Example output:

bash
file1.log:connection timeout
file3.log:request timeout

search patterns recursively across directories

To search across directories and subdirectories, use recursive search.

Example:

bash
grep -r "failed" /var/log

You can combine recursion with multiple patterns:

bash
grep -r -E "error|warning|critical" /var/log

How to Use grep Pattern From File (-f)

search multiple patterns using a pattern file with -f

The -f option allows grep to read patterns from a file.

Example pattern file:

bash
cat patterns.txt

Example contents:

bash
error
warning
failed

Search using the pattern file:

bash
grep -f patterns.txt logfile.txt

Grep will print lines that match any pattern listed in the file.

apply a pattern file across multiple input files

You can use the same pattern file to search across several files.

Example:

bash
grep -f patterns.txt file1.log file2.log file3.log

Example output:

bash
file1.log:error connecting to database
file2.log:authentication failed

This is useful when analyzing multiple log files at once.

filter log files using pattern files

Pattern files are commonly used for log filtering.

Example pattern file:

bash
cat alerts.txt

Contents:

bash
error
critical
failed

Use the file to filter logs:

bash
grep -f alerts.txt application.log

This command extracts all lines that contain important error keywords.

search directories recursively using pattern files

You can combine the pattern file with recursive search.

Example:

bash
grep -r -f patterns.txt /var/log

This scans all files under /var/log and prints lines matching any pattern in the pattern file.

ignore empty lines in grep pattern files

If a pattern file contains empty lines, grep may treat them as patterns.

Example pattern file:

bash
error
bash
warning

To ignore blank lines, you can clean the pattern file first:

bash
grep -v "^$" patterns.txt > cleaned_patterns.txt

Then run grep:

bash
grep -f cleaned_patterns.txt logfile.txt

perform case-insensitive searches with pattern files

You can combine the -f option with -i for case-insensitive searching.

Example:

bash
grep -i -f patterns.txt logfile.txt

This matches patterns regardless of case differences.

Example matches:

bash
ERROR
Error
error

combine pattern file search with extended regex

Pattern files can also contain regular expressions.

Example pattern file:

bash
[0-9]{3}
error|warning

Run grep with extended regex support:

bash
grep -E -f patterns.txt logfile.txt

This allows complex pattern matching.


Advanced Pattern Matching Scenarios

match lines containing two words in any order

Sometimes you need lines that contain two words anywhere in the line.

Example:

bash
grep -E "error.*database|database.*error" logfile.txt

This prints lines containing both error and database in any order.

match lines where a pattern appears multiple times

To match lines where a pattern appears repeatedly, use regex repetition.

Example:

bash
grep -E "(error.*){2,}" logfile.txt

This finds lines where the word error appears two or more times.

search text separated by tab characters

If two words are separated by a tab character, you can search using \t.

Example:

bash
grep $'user\tlogin' access.log

This matches lines where user and login are separated by a tab.

exclude lines containing a specific pattern

Use the -v option to exclude patterns.

Example:

bash
grep -v "debug" logfile.txt

This prints all lines except those containing debug.

extract text between two delimiters

Sometimes you need text between two markers.

Example:

bash
grep -oP '(?<=start).*?(?=end)' file.txt

This extracts text that appears between start and end.

match strings containing special characters

Special characters such as . or [ must be escaped.

Example:

bash
grep "\[" file.txt

This finds lines containing the [ character.

To search literal strings without regex interpretation:

bash
grep -F "a.b" file.txt

Real World grep Pattern Examples

find error messages in log files

To locate errors in logs:

bash
grep "error" application.log

For case-insensitive search:

bash
grep -i "error" application.log

detect failed login attempts in authentication logs

You can search authentication logs for failed logins.

Example:

bash
grep "Failed password" /var/log/auth.log

This helps identify potential brute-force login attempts.

extract IP addresses from server logs

To extract IPv4 addresses from logs:

bash
grep -E "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.log

Example output:

bash
192.168.1.20
10.0.0.8
172.16.0.15

search configuration parameters in configuration files

Grep can locate configuration values in files.

Example:

bash
grep "ListenPort" server.conf

This quickly finds the relevant configuration setting.

search multiple keywords in application logs

Example:

bash
grep -E "error|timeout|failed" application.log

This prints lines containing any of the specified keywords.

filter warning and error messages from logs

Example:

bash
grep -E "warning|error" system.log

This extracts important log entries.

search timestamps in log files

To find timestamps in logs:

bash
grep -E "[0-9]{2}:[0-9]{2}:[0-9]{2}" logfile.txt

This matches time patterns such as:

bash
14:32:11
09:45:02

Frequently Asked Questions

1. What is a pattern in grep?

A pattern in grep is a text string or regular expression used to search for matching lines in a file. Grep prints the lines that contain the specified pattern.

2. How do I search multiple patterns using grep?

You can search multiple patterns using the -E option with the pipe operator or by specifying multiple -e options. For example: grep -E 'error|fail' logfile.

3. How do I use regex with grep?

Grep supports regular expressions to perform advanced pattern matching such as character classes, anchors, and quantifiers.

4. How do I search patterns from a file using grep?

You can use the -f option to read patterns from a file. For example: grep -f patterns.txt file.txt.

5. What does 'grep: conflicting matchers specified' mean?

This error occurs when incompatible matching options like -E and -F are used together in the same grep command.

Summary

Mastering grep pattern matching allows system administrators and developers to filter massive datasets with surgical precision.

Key takeaways:

  • Use -F for literal strings and performance.
  • Use -E for modern, readable regex.
  • Use -P for advanced logic like lookaheads.
  • Use -f to manage large lists of search terms.

Further Reading

If you want to deepen your understanding of grep and related text-processing tools, explore the following tutorials:

You can also refer to the official documentation for more details:

Rohan Timalsina

Rohan Timalsina

is a technical writer and Linux enthusiast who writes practical guides on Linux commands and system administration. He focuses on simplifying complex topics through clear explanations.