The grep command in Linux with examples is one of the most useful tools you will ever learn. If you use Linux as your main OS, finding things quickly is often half the battle. Whether you are searching for a bug in a configuration file, reading through thousands of log lines, or trying to figure out which script called which function, the grep command in Linux is usually the first tool you reach for. It is fast, flexible, and available by default on almost all distributions.
This guide provides an overview of 10 grep command workflows based on three real-world search categories: basic search and filtering, advanced search options, and real-world system administration scenarios. If you’re just getting comfortable with the terminal, it’s best to start with our Linux commands for beginners guide first.
Note:
grep is part of the GNU coreutils package and comes pre-installed on Ubuntu, Rocky Linux, RHEL, Debian, Fedora, and virtually every Linux distribution. To check your version, run: grep --version
Examples
What Is grep?
grep Global Regular Expression Print is a tool used for searching for lines within one or more files, where those lines match a particular pattern you have provided. For each file it will read all of its lines and compare them to this pattern and print out every line which matches the pattern. As such as being able to perform a variety of actions with the aid of patterns, flags and piping, grep is one of the most valuable tools available to any Linux system administrator or developer.
This tool was written by Ken Thompson in 1974 as part of Unix. GNU grep is the most commonly used version on Linux systems today. It supports basic regular expressions (BRE), extended regular expressions (ERE, via egrep or grep -E), and fixed-string matching (via fgrep or grep -F). You can also use pgrep to find matching process names, but it works differently from standard grep.
grep works well on its own and even better when combined with pipes. You can pipe output from ps command, journalctl, cat, find, and dozens of other commands directly into grep to filter exactly what you need.
Syntax
The basic syntax of the grep command is:
LinuxTeck.com
Here is what each part means:
- OPTIONS — flags like -i, -r, -v, -n that change how grep behaves
- PATTERN — the string or regex you want to search for
- FILE — one or more files to search in; can also receive input via pipe
You can also read input from stdin using a pipe:
LinuxTeck.com
grep Options Reference Table
Below is a quick reference of the most commonly used grep flags covered in this article:
| Option | Description | Example |
|---|---|---|
| -i | Case-insensitive search | grep -i "error" file.txt |
| -n | Show line numbers | grep -n "pattern" file.txt |
| -c | Count matching lines | grep -c "pattern" file.txt |
| -v | Invert match (non-matching lines) | grep -v "pattern" file.txt |
| -w | Match whole words only | grep -w "word" file.txt |
| -e | Multiple patterns | grep -e "err" -e "warn" file.txt |
| -F | Fixed string, no regex | grep -F "[error]" file.txt |
| -o | Print only the matched part | grep -o "[0-9]\+" file.txt |
| -r | Recursive directory search | grep -r "pattern" /path/ |
| --include | Limit recursive search to file types | grep -r "pattern" --include="*.log" /var/log |
| --exclude | Skip matching files or dirs | grep -r "pattern" --exclude="*.txt" /path |
| --mtime | Search files modified in N days | grep -r "pattern" --mtime -7 /var/log |
| -A | Show N lines after match | grep -A 5 "pattern" file.txt |
| -B | Show N lines before match | grep -B 5 "pattern" file.txt |
| -C | Show N lines before and after match | grep -C 3 "pattern" file.txt |
| -P | Perl-compatible regex (PCRE) | grep -P "error.*failed" file.txt |
| -E | Extended regex (same as egrep) | grep -E "err|warn" file.txt |
| -a | Treat binary files as text | grep -a "pattern" file.bin |
| -l | Print only filenames with matches | grep -l "pattern" *.conf |
| -q | Quiet mode, no output (use for scripts) | grep -q "pattern" file.txt |
| --color=auto | Highlight matched text | grep --color=auto "pattern" file.txt |
grep Command in Linux With Examples - 10 Workflows
The 30 commands below are organized into three workflow categories:
Basic Search and Filter
Advanced Search Options
Real-World Usage Scenarios
Each category covers 10 commands with working examples and real output samples.
Workflow 1 - Basic Search & Filter
These are the day-to-day grep commands you will use constantly. Learning these 10 well will cover about 80% of real situations you run into on any Linux system.
I. Simple Search — Search for a pattern in a file
This is the most basic use of grep. You give it a pattern and a filename, and it prints every line that contains that pattern. It is case-sensitive by default.
LinuxTeck.com
Another line with pattern here too.
Tip:
If your pattern has spaces, wrap it in quotes. Single quotes prevent shell expansion of special characters, double quotes allow variable substitution inside the pattern.
II. Ignore Case — Search without case sensitivity
Add the -i flag to make your search case-insensitive. This is very useful when searching logs where the same word may appear as ERROR, Error, or error depending on the application that wrote it.
LinuxTeck.com
PATTERN also matches this line.
pattern in lowercase too.
III. Show Line Numbers — Display matching lines with numbers
The -n flag prepends each matching line with its line number. This is extremely useful when you need to jump to a specific location in a config file or script to make an edit.
LinuxTeck.com
37:Another match found here.
IV. Count Matches — Count total matching lines
The -c flag tells grep to print just the count of matching lines instead of the lines themselves. Good for quick audits: how many times did this event appear in the log today?
LinuxTeck.com
Note:
-c counts lines with at least one match, not the total number of matches per line. A line with the pattern appearing three times still counts as 1.
V. Invert Match — Show lines that do NOT match
The -v flag inverts the search logic. Instead of printing lines that match, it prints every line that does not match. Very useful for filtering out noise from log files or config files.
LinuxTeck.com
This line is shown because it has no match.
VI. Match Whole Word — Match whole words only
By default, grep matches any occurrence of your pattern even if it is part of a longer word. For example, searching for "log" would also match "syslog" and "catalog". The -w flag restricts the match to whole words only.
LinuxTeck.com
(lines containing "keyword" or "password" are NOT shown)
VII. Multiple Patterns — Match any of the given patterns
Use the -e flag to supply multiple search patterns in a single grep command. grep will return any line that matches at least one of the patterns. You can stack as many -e options as you need.
LinuxTeck.com
May 04 08:15:01 server1 systemd: warn: service nginx failed to start
Tip:
You can also write this as: grep -E "err|warn" file.txt using extended regex. Both do the same thing.
VIII. Fixed String Search — Treat pattern as plain text, no regex
When your search string contains special regex characters like brackets, dots, asterisks, or parentheses, grep may misinterpret them. The -F flag disables regex entirely and treats your pattern as a plain fixed string. This also runs faster than regex on large files.
LinuxTeck.com
IX. Show Only Matches — Print only the matched part
The -o flag tells grep to print only the part of each line that matched the pattern, not the entire line. Very useful when you want to extract specific data like IP addresses, timestamps, or error codes from large log files.
LinuxTeck.com
200
500
301
X. Limit Results — Show only first N matching lines
Pipe grep output to head -n to limit how many matching lines you see. This is useful when a pattern has hundreds of matches and you just need a quick sample to understand what is happening.
LinuxTeck.com
Workflow 2 - Advanced Search Options
These 10 commands go beyond simple text matching. They let you search across entire directory trees, target specific file types, look at the lines surrounding a match, and use powerful regex engines to find complex patterns.
XI. Search in Files Recursively — Search through files in directories
The -r flag makes grep walk into subdirectories and search every file it finds. This is one of the most useful grep options for developers and sysadmins who need to find where a variable, function, or config value is used across a whole project or system path.
LinuxTeck.com
/path/to/dir/subdir/app.conf:pattern found here too
Note:
On large directory trees like /etc or /var, recursive grep can be slow. Combine with --include to narrow it down to specific file types, shown in the next example.
XII. Include Only Specific Files — Search in specific file types
Use --include with the -r flag to restrict your recursive search to only files matching a certain pattern. For example, search only in .log files, or only in .conf files. This saves a lot of time on busy servers.
LinuxTeck.com
/var/log/syslog:May 04 09:22:11 server pattern in syslog
XIII. Exclude Files or Directories — Skip files or directories while searching
The --exclude flag is the opposite of --include. You can tell grep to skip certain file types or directory names when doing a recursive search. Combine --exclude-dir to skip entire directories like .git or node_modules.
LinuxTeck.com
grep -r "pattern" --exclude-dir=".git" /path
(all .txt files and .git directory are skipped)
XIV. Search by Modified Time — Search files modified in the last N days
Combine grep with the find command to search only in files that were modified recently. This is especially useful on active servers where log files rotate daily and you only care about recent changes.
LinuxTeck.com
/var/log/syslog.1:May 02 pattern appears here
Tip:
Use -mtime -1 to search only files modified in the last 24 hours. Use xargs -0 with find -print0 to safely handle filenames that contain spaces.
XV. Show Context Before and After — Show N lines before and after match
The -C flag prints N lines of context both before and after each matching line. This is one of the most practical grep options for debugging because it shows you what happened just before and after an error event in a log file.
LinuxTeck.com
3 lines before the match...
3 lines before the match...
-- MATCHED LINE: pattern found here --
3 lines after the match...
3 lines after the match...
3 lines after the match...
XVI. Show Only Before Match — Show N lines before the match
The -B flag is like -C but only shows lines before the match. Useful when you want to see what led up to an event without seeing what came after.
LinuxTeck.com
5 context lines before...
5 context lines before...
5 context lines before...
5 context lines before...
MATCHED LINE: pattern found here
XVII. Show Only After Match — Show N lines after the match
The -A flag is the counterpart to -B. It shows lines after the match. Useful when a log entry triggers a chain of messages and you want to see the full sequence of what happened after the event.
LinuxTeck.com
5 context lines after...
5 context lines after...
5 context lines after...
5 context lines after...
5 context lines after...
XVIII. Match Multiple Lines with Regex — Use extended or Perl regex for complex search
Use -P for Perl-Compatible Regular Expressions (PCRE) when you need complex pattern matching like lookaheads, non-greedy quantifiers, or multiline patterns. The example below finds lines where "error" is followed eventually by "failed".
LinuxTeck.com
Warning:
-P (PCRE) may not be available on all systems. Alpine Linux and some minimal containers use BusyBox grep which does not support PCRE. Use grep -E for extended regex as a safer cross-distro option.
XIX. Search Binary Files — Search in binary files too
By default, grep skips binary files or prints "Binary file matches". The -a flag forces grep to treat binary files as text and search through them. Useful when you are digging through compiled files or memory dumps looking for readable strings.
LinuxTeck.com
XX. Color Highlighting — Highlight matches in color
The --color=auto flag highlights matched text in red (or whatever your terminal color scheme uses). On most modern distros, this is already enabled by default via a shell alias. If it is not, add it manually or set GREP_OPTIONS in your .bashrc.
LinuxTeck.com
# To make it permanent, add to ~/.bashrc:
alias grep='grep --color=auto'
Workflow 3 - Real-World Usage Scenarios
This is where grep really earns its place in your daily workflow. The following 10 examples cover the exact tasks that sysadmins on Ubuntu, Rocky Linux, and RHEL deal with regularly. These are not textbook examples. They are commands you will actually run on production systems.
XXI. Find Errors in Logs — Find all error lines in logs
One of the most common sysadmin tasks is scanning log files for errors. Use grep -i "error" against your log directory to pull all error lines from all log files in one shot. On Ubuntu systems, look in /var/log/syslog. On Rocky Linux and RHEL, check /var/log/messages.
LinuxTeck.com
grep -i "error" /var/log/syslog
# Rocky Linux / RHEL
grep -i "error" /var/log/messages
# All log files in /var/log
grep -i "error" /var/log/*.log
May 04 08:15:44 server1 mysqld: ERROR 1045 Access denied for user 'root'
Tip:
Combine with journalctl on systemd-based systems: journalctl -xe | grep -i "error" for a live filtered view of recent errors across all services.
XXII. Find Warnings — Find warning messages
Warnings often signal a problem that has not yet broken anything. Catching them early can prevent bigger incidents later. Use the same approach as error searching but target the word "warn".
LinuxTeck.com
May 04 08:02:31 server1 kernel: WARNING: CPU thermal throttling
XXIII. Search IP Address — Find lines containing an IP address
You can use grep with extended regex to find lines containing patterns that look like IPv4 addresses. This works great on web server access logs and firewall logs when you are investigating suspicious traffic.
LinuxTeck.com
10.0.0.2 - - [04/May/2026:09:00:05 +0000] "POST /login HTTP/1.1" 401 512
XXIV. Find Specific User Activity — Search entries for a specific user
On a multi-user Linux server, you often need to check what a specific user has been doing. The auth.log (Ubuntu/Debian) or secure log (Rocky/RHEL) records all authentication and sudo activity per user. For checking running user processes, you can also combine this with the ps command in Linux.
LinuxTeck.com
grep "username" /var/log/auth.log
# Rocky Linux / RHEL
grep "username" /var/log/secure
May 04 10:18:01 server1 sudo: username : TTY=pts/1 ; COMMAND=/bin/systemctl restart nginx
XXV. Find HTTP 404 Errors — Find 404 errors in web server logs
Quickly spot all 404 Not Found responses in your nginx or Apache access log. High volumes of 404s from the same IP can indicate a bot scanning your site for vulnerabilities.
LinuxTeck.com
grep " 404 " /var/log/httpd/access_log
203.0.113.7 - - [04/May/2026:09:30:15 +0000] "GET /.env HTTP/1.1" 404 162
Warning:
Repeated 404 probes for paths like /.env, /wp-login.php, or /phpmyadmin from a single IP are a strong sign of automated scanning. Consider blocking the IP using firewalld or fail2ban.
XXVI. Search in Config Files — Find a setting in config files
When you need to know which config file has a specific directive set, recursive grep on /etc is your fastest option. This saves a lot of time compared to manually opening files one by one.
LinuxTeck.com
/etc/nginx/sites-enabled/default:listen 80 default_server;
XXVII. Find Running Service — Check if a service is running
Pipe ps aux output into grep to instantly check whether a specific service or process is running. The -i flag makes it case-insensitive. This is faster than running systemctl status when you just need a quick yes or no answer.
LinuxTeck.com
www-data 1024 0.0 0.2 55820 4096 ? S 08:00 0:00 nginx: worker process
Note:
grep itself will show up in the ps output. Add grep -v grep to the pipe to remove it: ps aux | grep -i nginx | grep -v grep
XXVIII. Check Disk Usage — Find large files using du output
You can pipe du output into grep to filter disk usage reports. For example, find all directories or files that show gigabyte-level usage. This is useful when a partition is filling up and you need to track down where the space went. For a deeper look at disk usage monitoring, see our guide on the df command in Linux.
LinuxTeck.com
1.8G /home/user/backups
2.1G /opt/app/data
XXIX. View Crontab Entries — Search specific job in crontab
When you manage many servers and cron jobs, finding a specific scheduled task quickly matters. Run crontab -l and pipe it to grep, or search the system-wide cron directories directly. For more on scheduling automation, check our full cron command guide.
LinuxTeck.com
# Search system-wide cron jobs
grep -r "backup" /etc/cron* /var/spool/cron/
XXX. Search in Multiple Files — Search pattern in multiple files
You can give grep multiple file names directly on the command line to search across all of them in one pass. grep will prefix each output line with the filename so you always know which file the match came from.
LinuxTeck.com
file3.txt:another line with pattern in file3
Using grep Inside Bash Scripts
How grep works inside shell scripts. In real sysadmin and DevOps work, you rarely run grep as a standalone interactive command. You embed it in scripts to drive logic.
grep returns an exit code after every run. Exit code 0 means at least one match was found. Exit code 1 means no match. Exit code 2 means an error occurred (bad option, missing file). You can use these in if/else conditions inside your scripts.
LinuxTeck.com
# Check if nginx is running, take action based on result
if ps aux | grep -q "nginx"; then
echo "nginx is running"
else
echo "nginx is NOT running — attempting restart"
systemctl start nginx
fi
The -q flag (quiet mode) suppresses all output and just returns the exit code. This is the correct way to use grep inside scripts when you only care about whether something matched, not what matched.
LinuxTeck.com
# Search log for critical errors and alert
LOG="/var/log/syslog"
PATTERN="Out of memory"
if grep -qi "$PATTERN" "$LOG"; then
echo "[ALERT] OOM event detected in $LOG"
grep -i "$PATTERN" "$LOG" | tail -5
fi
Tip:
Always quote your variables when using grep in scripts: grep "$PATTERN" "$FILE" — unquoted variables break when filenames or patterns contain spaces.
grep vs egrep vs fgrep — What Is the Difference?
This is one of the most searched questions about grep. Here is a clear breakdown:
| Command | Equivalent to | Regex Type | When to Use |
|---|---|---|---|
| grep | grep (BRE) | Basic Regular Expressions | Most standard searches; default tool |
| egrep | grep -E | Extended Regular Expressions | When you need +, ?, |, () without escaping |
| fgrep | grep -F | No regex (fixed strings) | When searching for literal special characters like . * [ ] |
| pgrep | grep on process names | Basic regex | Finding process IDs by name; works differently from file grep |
In practice, egrep and fgrep are deprecated aliases on GNU systems. The recommended approach is to use grep -E and grep -F instead. They are still available on most systems for backward compatibility but new scripts should use the flag forms.
LinuxTeck.com
egrep "error|warn" file.txt
grep -E "error|warn" file.txt
# These are also equivalent:
fgrep "[error]" file.txt
grep -F "[error]" file.txt
grep Performance Tips for Large Files
On production servers with multi-gigabyte log files, a slow grep can take minutes or even time out. These are practical tips that can make grep run significantly faster on large files.
1. Use LC_ALL=C to speed up grep on large text files
By default, grep uses your system locale to handle character encoding. On multi-byte locales like UTF-8, this adds processing overhead. Setting LC_ALL=C forces single-byte processing and can make grep 3x to 10x faster on large ASCII log files.
LinuxTeck.com
2. Use -F for fixed strings when no regex is needed
If your search pattern has no special characters, always use -F. Fixed string search skips the regex engine entirely and is noticeably faster.
LinuxTeck.com
3. Combine LC_ALL=C with -F for maximum speed
LinuxTeck.com
Note:
If your log files contain non-ASCII characters (for example, user input or application data with accented characters), LC_ALL=C may miss those lines. Test on a sample before using on production data.
Troubleshooting Common grep Problems
This section covers the most common issues people run into with grep.
Problem 1: "grep: command not found"
This happens on minimal container images (Alpine, BusyBox-based). Install grep with the appropriate package manager:
LinuxTeck.com
sudo apt install grep
# Rocky Linux / RHEL / Fedora
sudo dnf install grep
# Alpine Linux
apk add grep
Problem 2: "Binary file matches" — grep skipping a file
grep detects binary content and shows this message instead of output. Either use -a to force text mode, or use strings to extract readable content first:
LinuxTeck.com
strings binaryfile | grep "pattern"
Problem 3: grep returns no output but you know the pattern exists
Most likely a case sensitivity issue. Try adding -i. Also check that you have read permission on the file. Check if there are hidden characters (Windows-style CRLF line endings) using cat -A to see them.
LinuxTeck.com
cat -A file.txt | grep "pattern"
Problem 4: grep hangs on very large files
This can happen with complex regex patterns (catastrophic backtracking) or huge files. Use LC_ALL=C, switch to -F for fixed strings, or limit with head to test a sample first:
LinuxTeck.com
LC_ALL=C grep -F "pattern" /var/log/huge-file.log
Why grep Matters for Linux Sysadmins and DevOps
grep is more than just a tool for searching text. It plays a key role in debugging, monitoring, and automating tasks in Linux. It has been around for more than 50 years and remains widely used because it does one thing well and integrates seamlessly with other Unix tools through pipes.
If you are a system administrator managing Ubuntu servers, Rocky Linux clusters, or RHEL enterprise deployments, grep is a tool you use every day to respond to incidents. You won’t be able to rely on a GUI when a service fails at midnight. Instead, you use grep on logs, systemctl status, and journalctl to identify the problem in less than a minute.
For DevOps engineers and developers, grep is how you search codebases, trace config values across deployment environments, and validate that scripts are producing the expected output. When combined with tools like sed command in Linux, awk, and find, grep becomes part of a powerful text processing pipeline that can handle almost any data transformation task without needing a specialized tool.
Learning grep properly also builds the foundation for understanding regular expressions, which are used across Python, JavaScript, Perl, Rust, and virtually every modern programming language. Time spent mastering grep is never wasted.
Key Takeaways
- grep searches files line by line for a pattern and prints matching lines. It is pre-installed on Ubuntu, Rocky Linux, RHEL, and all major Linux distros.
- The three core workflow categories are: Basic Search and Filter (10 commands), Advanced Search Options (10 commands), and Real-World Sysadmin Scenarios (10 commands).
- Use -i for case-insensitive search, -r for recursive directory search, -v to invert the match, and -n to show line numbers.
- Use -C, -A, -B to show context lines around a match — essential for log debugging where you need to see what happened before and after an event.
- Use -F for fixed string search when your pattern contains no regex. It is faster than regex and prevents accidental misinterpretation of special characters.
- Use -q in Bash scripts to silently test for a pattern and act on the exit code. grep returns 0 for match, 1 for no match, 2 for error.
- Set LC_ALL=C before grep to dramatically speed up searches on large ASCII log files by forcing single-byte character processing.
- egrep is grep -E (extended regex) and fgrep is grep -F (fixed strings). Both are deprecated aliases; use the flag forms in new scripts.
- On Rocky Linux and RHEL, key log files are /var/log/messages and /var/log/secure. On Ubuntu and Debian they are /var/log/syslog and /var/log/auth.log.
- Combine grep with find, ps aux, journalctl, du, crontab, and other standard tools via pipes to create powerful one-liner diagnostics.
People Also Ask
What is the difference between grep, egrep, and fgrep?
grep uses Basic Regular Expressions (BRE) by default. egrep (equivalent to grep -E) uses Extended Regular Expressions which support additional metacharacters like +, ?, and | without needing backslash escapes. fgrep (equivalent to grep -F) treats the pattern as a plain fixed string with no regex processing at all. On modern GNU systems, egrep and fgrep are deprecated aliases. The recommended approach is to use grep -E and grep -F in all new scripts.
How do I grep for multiple patterns in Linux?
There are two clean ways to do this. First, use multiple -e flags: grep -e "error" -e "warn" file.txt. Second, use extended regex with the pipe operator: grep -E "error|warn" file.txt. Both approaches return any line that matches at least one of the given patterns. You can stack as many patterns as you need with either method.
How do I use grep to search all files in a directory recursively?
Use the -r flag followed by the directory path: grep -r "pattern" /path/to/directory. This searches all files in the directory and all subdirectories. To limit the search to specific file types, add --include: grep -r "pattern" --include="*.conf" /etc/. To skip certain file types or directories, use --exclude or --exclude-dir.
How do I use grep in a Bash script without printing output?
Use the -q (quiet) flag. With -q, grep produces no output but still returns an exit code: 0 if a match was found, 1 if not. In a script you use it like this: if grep -q "pattern" file.txt; then echo "found"; fi. This is the standard and recommended way to use grep inside shell scripts when you only need to know whether something matched.
Why is grep slow on large log files and how do I speed it up?
Two main reasons: complex regex patterns and multi-byte locale processing. To speed up grep, first set LC_ALL=C before the command to force single-byte processing: LC_ALL=C grep "pattern" file.log. Second, if your pattern has no special regex characters, use -F for fixed string matching which skips the regex engine entirely: LC_ALL=C grep -F "error" file.log. Together these two changes can make grep several times faster on large ASCII log files.
What are the key log file locations for grep on Ubuntu vs Rocky Linux?
On Ubuntu and Debian-based systems, the main system log is /var/log/syslog and authentication events are in /var/log/auth.log. Web server logs are in /var/log/nginx/ or /var/log/apache2/. On Rocky Linux, RHEL, and CentOS, the main system log is /var/log/messages and security/authentication events are in /var/log/secure. Apache logs are in /var/log/httpd/. On all systemd-based systems you can also use journalctl | grep "pattern" to search structured system journal logs.
For the complete list of grep options and flags, refer to the official
GNU grep manual.
From your first terminal command to advanced sysadmin skills — every guide here is written in plain English with real examples you can run right now.