grep – Practical Search on Linux Shell
The grep command searches text for patterns. It’s a powerful tool for quickly finding information inside files or command outputs.
Basic Syntax
grep [OPTIONS] PATTERN [FILE...]
PATTERN: Text or regular expression to search for.FILE: One or more files to search in. If none, reads from stdin.
Options
| Option | Description |
|---|---|
-i |
Case-insensitive search |
-r or -R |
Recursive search in directories |
-v |
Invert match (show lines NOT matching) |
-n |
Show line numbers |
-l |
Show filenames with matches only |
-c |
Count matching lines per file |
--color |
Highlight matches in output (usually enabled) |
Practical Everyday Examples
1. Search for a word in a single file
grep "error" /var/log/syslog
Find all lines containing “error” in the system log.
2. Case-insensitive search
grep -i "warning" /var/log/syslog
Find “warning”, “Warning”, or “WARNING”.
3. Search recursively in a directory
grep -r "TODO" ~/projects/
Find all TODO comments in your project files.
4. Show line numbers with matches
grep -n "fail" /var/log/auth.log
Quickly jump to exact lines where “fail” appears.
5. Count how many times a word appears in a file
grep -c "sshd" /var/log/auth.log
6. Show only filenames with matches
grep -l "main()" *.c
List C files containing main().
7. Invert match — show lines without the pattern
grep -v "DEBUG" app.log
Filter out all debug messages from logs.
8. Search command output (use pipe |)
dmesg | grep -i "usb"
Find USB-related kernel messages.
9. Search multiple patterns (OR) with -E (extended regex)
grep -E "error|fail|warning" /var/log/syslog
10. Use grep to filter process list
ps aux | grep apache
11. Search whole words only (-w)
grep -w "cat" file.txt
Avoid matching words like “catalog”.
12. Use context options: show lines before/after matches
grep -C 2 "error" app.log
Show 2 lines before and after each match for better context.
13. Search hidden files/directories recursively
grep -r --exclude-dir=".git" "fixme" .
Search everywhere except .git.
14. Save grep output to a file
grep "fail" /var/log/syslog > fails.txt
15. Colorize output for better visibility (if not default)
grep --color=always "pattern" file.txt
Combining grep with Other Tools
Filter and count unique IPs in Apache logs
grep "GET" access.log | awk '{print $1}' | sort | uniq -c | sort -nr
Find processes running more than 100 MB RAM
ps aux | grep apache | awk '$6 > 100000'
Find TODOs and fixme comments in code (recursive)
grep -riE "todo|fixme" ./src/
Tips & Tricks
- Use
grep -rwith--excludeor--exclude-dirto skip files or directories. - Combine with
headortailto view only first or last matches. - Use
xargsto apply commands on grep results, e.g.:
grep -rl "TODO" . | xargs wc -l
More Resources
man grep
info grep
Feel free to ask if you want examples for regex, scripting use cases, or log monitoring with grep!