The grep command in Linux is a powerful text-search utility that scans files or input streams for lines matching a specified pattern using regular expressions. Short for “Global Regular Expression Print,” grep is indispensable for filtering logs, analyzing code, and extracting specific data.
- Basic Text Search
- Case-Insensitive Search
- Recursive Search in Directories
- Display Line Numbers
- Count Matching Lines
- Invert Match (Exclude Lines)
- Pipe Input from Another Command
- Use Regular Expressions (Email Pattern)
- Search Multiple Files with Wildcards
- Combine with find for Advanced Searches
- Search Compressed Files
- Display Context Around Matches
- Extended Grep (egrep) for Multiple Patterns
- Search for a String in Command Output
Basic Text Search
grep "error" logfile.txt
Searches for the word “error” in logfile.txt
and prints matching lines.
Case-Insensitive Search
grep -i "warning" logfile.txt
-i
ignores case, matching “Warning”, “WARNING”, etc.
Recursive Search in Directories
grep -r "TODO" /path/to/project
-r
searches recursively through all files in the directory.
Display Line Numbers
grep -n "404" access.log
-n
shows line numbers for matches (e.g.,42:404 Not Found
).
5. Highlight Matches
grep --color=auto "success" output.log
Highlights the matched text in color for easier visibility.
Count Matching Lines
grep -c "GET" access.log
-c
returns the number of lines containing “GET”.
Invert Match (Exclude Lines)
grep -v "debug" app.log
-v
prints lines not containing “debug”.
8. Search for Whole Words
grep -w "port" config.txt
-w
matches “port” as a whole word (ignores substrings like “export”).
Pipe Input from Another Command
cat access.log | grep "POST"
Filters the output of cat
to show lines with “POST”.
Use Regular Expressions (Email Pattern)
grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}" users.txt
-E
enables extended regex to match email addresses.
Search Multiple Files with Wildcards
grep "panic" *.log
Searches for “panic” in all .log
files in the current directory.
Combine with find for Advanced Searches
find /var/log -type f -name "*.log" -exec grep "failed" {} \;
Searches for “failed” in all .log
files under /var/log
.
Search Compressed Files
zgrep "error" /var/log/syslog.1.gz
Searches inside gzipped files without decompressing them.
Display Context Around Matches
grep -C3 "crash" app.log
-C3
shows 3 lines before and after the matching line.- Use
-B
(before) or-A
(after) for one-directional context.
Extended Grep (egrep) for Multiple Patterns
egrep "error|warning|critical" system.log
Matches lines containing “error”, “warning”, or “critical”.
Search for a String in Command Output
ps aux | grep "firefox"
Filters processes to show only those related to firefox.
Key Notes:
- Regular Expressions: Use
grep -E
oregrep
for advanced patterns. - Performance: Avoid
grep
on huge files—use tools likeless
orawk
instead. - Exclude Directories: Add
--exclude-dir=.git
to skip specific folders in recursive searches.