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.
grep "error" logfile.txtIn 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 Type | Description | Example |
|---|---|---|
| Simple text pattern | Searches exact string | grep error file.log |
| Regular expression | Searches using regex rules | grep '[0-9]' file.txt |
| Fixed string search | Treats pattern as literal text | grep -F 'a.b' file.txt |
Different options allow grep to use different pattern engines.
| Option | Pattern Type |
|---|---|
| default grep | Basic regular expressions |
| -E | Extended regular expressions |
| -P | Perl compatible regex |
| -F | Fixed string search |
grep Pattern Matching Quick Reference
The following table provides quick examples of commonly used grep pattern scenarios.
| Scenario | Example Command |
|---|---|
| Search a simple text pattern | grep "error" logfile.txt |
| Ignore case while searching | grep -i "error" logfile.txt |
| Match whole word only | grep -w "error" logfile.txt |
| Print only matching pattern | grep -o "[0-9]*" file.txt |
| Search multiple patterns (OR) | grep -E "error |
| Search patterns using multiple -e options | grep -e error -e warning logfile.txt |
| Read patterns from file | grep -f patterns.txt logfile.txt |
| Print line numbers with match | grep -n "error" logfile.txt |
| Print lines after match | grep -A 3 "error" logfile.txt |
| Print lines before match | grep -B 3 "error" logfile.txt |
| Print lines before and after match | grep -C 3 "error" logfile.txt |
| Recursive search in directories | grep -r "error" /var/log |
| Search fixed string pattern | grep -F "a.b" file.txt |
| Use extended regex | grep -E "[0-9]{3}" file.txt |
| Use Perl compatible regex | grep -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:
grep "error" logfile.txtThis command searches for the word error inside logfile.txt and prints all matching lines.
You can also search command output using pipes:
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:
grep "warning" system.logIf 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:
grep -c "warning" system.logmatch 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:
grep -w "error" logfile.txtThis ensures only the complete word error is matched.
print only the matched pattern using -o
By default, grep prints the entire line that contains a match. The -o option prints only the matching portion.
Example:
grep -o "[0-9]*" numbers.txtThis extracts only numeric values from the file.
Example output:
42
105
678search patterns ignoring case
By default grep is case sensitive. The -i option allows case-insensitive searching.
Example:
grep -i "error" logfile.txtThis matches:
- error
- Error
- ERROR
This is useful when searching logs where case may vary.
print line numbers with matching pattern
The -n option prints the line number along with the matching line.
Example:
grep -n "failed" auth.logExample output:
23:Failed password for root
45:Failed password for adminThis 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:
grep -r "database" /etc/This searches every file under /etc for the word database.
You can also restrict the search to specific file types:
grep -r "error" --include="*.log" /var/loggrep Regex Examples & Advanced Patterns
match numeric patterns using regex
To match numbers in a file, you can use a character class.
Example:
grep "[0-9]" file.txtThis finds lines containing at least one digit.
To match sequences of numbers:
grep "[0-9]\+" file.txtmatch alphabetic strings
To search lines that contain alphabetic characters only, use a letter range.
Example:
grep "^[a-zA-Z]*$" file.txtThis matches lines containing only letters.
match lines starting with specific characters
The caret ^ represents the start of a line.
Example:
grep "^Error" logfile.txtThis finds lines that start with the word Error.
Example output:
Error connecting to database
Error reading configurationmatch lines starting with specific characters
The dollar sign $ represents the end of a line.
Example:
grep "failed$" logfile.txtThis 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.
grep "\b[a-zA-Z]\{5\}\b" file.txtThis matches words containing exactly five letters.
match alphanumeric patterns
To match alphanumeric patterns, combine character classes.
Example:
grep "[a-zA-Z][0-9]" file.txtThis finds patterns where letters are followed by numbers.
Example matches:
user1
id2extract structured text using regex
You can extract structured patterns such as email addresses.
Example:
grep -o "[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]*" file.txtThis prints only the email addresses found in the file.
extract IP addresses from text
You can use regex to extract IPv4 addresses.
Example:
grep -E "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.logExample output:
192.168.1.10
10.0.0.5
172.16.0.22This 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:
grep -E "error|warning" logfile.txtThis prints lines containing either error or warning.
search multiple patterns using -e option
You can specify multiple patterns using the -e option.
Example:
grep -e error -e warning -e critical logfile.txtThis searches for all three patterns.
match multiple patterns using regex pipe operator
The pipe operator | can also be used to combine patterns.
Example:
grep -E "failed|denied|invalid" auth.logThis 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:
grep -P "(?=.*error)(?=.*database)" logfile.txtThis prints lines containing both error and database.
search patterns from multiple files
You can search multiple files in one command.
Example:
grep "timeout" file1.log file2.log file3.logGrep prints matches along with the filename.
Example output:
file1.log:connection timeout
file3.log:request timeoutsearch patterns recursively across directories
To search across directories and subdirectories, use recursive search.
Example:
grep -r "failed" /var/logYou can combine recursion with multiple patterns:
grep -r -E "error|warning|critical" /var/logHow 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:
cat patterns.txtExample contents:
error
warning
failedSearch using the pattern file:
grep -f patterns.txt logfile.txtGrep 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:
grep -f patterns.txt file1.log file2.log file3.logExample output:
file1.log:error connecting to database
file2.log:authentication failedThis 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:
cat alerts.txtContents:
error
critical
failedUse the file to filter logs:
grep -f alerts.txt application.logThis 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:
grep -r -f patterns.txt /var/logThis 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:
errorwarningTo ignore blank lines, you can clean the pattern file first:
grep -v "^$" patterns.txt > cleaned_patterns.txtThen run grep:
grep -f cleaned_patterns.txt logfile.txtperform case-insensitive searches with pattern files
You can combine the -f option with -i for case-insensitive searching.
Example:
grep -i -f patterns.txt logfile.txtThis matches patterns regardless of case differences.
Example matches:
ERROR
Error
errorcombine pattern file search with extended regex
Pattern files can also contain regular expressions.
Example pattern file:
[0-9]{3}
error|warningRun grep with extended regex support:
grep -E -f patterns.txt logfile.txtThis 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:
grep -E "error.*database|database.*error" logfile.txtThis 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:
grep -E "(error.*){2,}" logfile.txtThis 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:
grep $'user\tlogin' access.logThis 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:
grep -v "debug" logfile.txtThis prints all lines except those containing debug.
extract text between two delimiters
Sometimes you need text between two markers.
Example:
grep -oP '(?<=start).*?(?=end)' file.txtThis extracts text that appears between start and end.
match strings containing special characters
Special characters such as . or [ must be escaped.
Example:
grep "\[" file.txtThis finds lines containing the [ character.
To search literal strings without regex interpretation:
grep -F "a.b" file.txtReal World grep Pattern Examples
find error messages in log files
To locate errors in logs:
grep "error" application.logFor case-insensitive search:
grep -i "error" application.logdetect failed login attempts in authentication logs
You can search authentication logs for failed logins.
Example:
grep "Failed password" /var/log/auth.logThis helps identify potential brute-force login attempts.
extract IP addresses from server logs
To extract IPv4 addresses from logs:
grep -E "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.logExample output:
192.168.1.20
10.0.0.8
172.16.0.15search configuration parameters in configuration files
Grep can locate configuration values in files.
Example:
grep "ListenPort" server.confThis quickly finds the relevant configuration setting.
search multiple keywords in application logs
Example:
grep -E "error|timeout|failed" application.logThis prints lines containing any of the specified keywords.
filter warning and error messages from logs
Example:
grep -E "warning|error" system.logThis extracts important log entries.
search timestamps in log files
To find timestamps in logs:
grep -E "[0-9]{2}:[0-9]{2}:[0-9]{2}" logfile.txtThis matches time patterns such as:
14:32:11
09:45:02Frequently 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
-Ffor literal strings and performance. - Use
-Efor modern, readable regex. - Use
-Pfor advanced logic like lookaheads. - Use
-fto 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:
- 20 grep command examples in Linux [Cheat Sheet]
- Easy regex to grep exact match with examples
- 3 simple and useful tools to grep multiple strings in Linux
- AWK Command in Linux: Complete Guide with Practical Examples
You can also refer to the official documentation for more details:


![15+ Tips to PROPERLY sort files in Linux [Cheat Sheet]](/linux-sort-files/sort_command_hu_f153d60b2b55d5b6.webp)
![9 screen command Examples in Linux [Cheat Sheet]](/screen-command-in-linux/screen_command-1_hu_5e60e89880f98ac2.webp)
![Increase load with stress command in Linux [Cheat Sheet]](/stress-command-in-linux/stress_command_hu_7b5119be5f0060f4.webp)

![10+ traceroute command in Linux [Cheat Sheet]](/traceroute-command-in-linux/traceroute_command_hu_9e60fd6575e1c7c2.webp)
![10+ tcpdump command examples in Linux [Cheat Sheet]](/tcpdump-command-in-linux/tcpdump_command_hu_28e7fff8995c4ce8.webp)
![10+ mke2fs command examples in Linux [Cheat Sheet]](/mke2fs-command-in-linux/mke2fs_command_hu_e526d401d8929c5.webp)
