grep – search for patterns in files

grep searches for patterns in files and prints matching lines. It’s one of the most essential Unix tools for finding text.
Synopsis
grep [OPTIONS] PATTERN [FILE...]
Common Options
| Option | Description |
|---|---|
-i | Case-insensitive search |
-v | Invert match (show non-matching lines) |
-r | Recursive search in directories |
-n | Show line numbers |
-c | Count matching lines only |
-l | List filenames with matches only |
-w | Match whole words only |
-A N | Show N lines after match |
-B N | Show N lines before match |
-C N | Show N lines before and after (context) |
-E | Extended regex (same as egrep) |
Examples
Basic search
$ grep ubuntu /etc/hosts
127.0.1.1 ubuntu
Case-insensitive search
$ grep -i error /var/log/syslog
Jan 15 10:23:45 server ERROR: Connection failed
Jan 15 10:24:01 server error: timeout
Search recursively in directory
$ grep -r "TODO" ~/project/
src/main.py:# TODO: refactor this
src/utils.py:# TODO: add error handling
Show line numbers
$ grep -n root /etc/passwd
1:root:x:0:0:root:/root:/bin/bash
Count matches
$ grep -c error /var/log/syslog
42
Show context (lines around match)
$ grep -C 2 "fatal" /var/log/messages
Jan 15 10:20:00 server starting service
Jan 15 10:20:01 server connecting to database
Jan 15 10:20:02 server fatal: connection refused
Jan 15 10:20:03 server shutting down
Jan 15 10:20:04 server cleanup complete
List files containing pattern
$ grep -l "import os" *.py
main.py
utils.py
config.py
Invert match (exclude lines)
$ grep -v "^#" /etc/ssh/sshd_config | grep -v "^$"
Port 22
PermitRootLogin no
PasswordAuthentication yes
Match whole words only
$ grep -w "the" file.txt # matches "the" but not "there" or "other"
Regular Expressions
grep supports basic regular expressions by default:
| Pattern | Meaning |
|---|---|
. | Any single character |
* | Zero or more of previous |
^ | Start of line |
$ | End of line |
[abc] | Character class |
[^abc] | Negated character class |
Find lines starting with a word
$ grep "^root" /etc/passwd
root:x:0:0:root:/root:/bin/bash
Find empty lines
$ grep "^$" file.txt
Extended regex (-E or egrep)
$ grep -E "error|warning|fatal" /var/log/syslog
Tips
- Combine with find:
find . -name "*.log" -exec grep "error" {} + - Use
--colorfor highlighted matches (often default in modern systems) - Pipe to grep:
ps aux | grep nginx - Exclude directories:
grep -r --exclude-dir=.git "pattern" . - Binary files: Use
-ato treat binary as text, or-Ito skip them
See Also
Related Commands
- awk — Pattern scanning and processing
- sed — Stream editor for filtering text
- find — Search for files
- less — View files with search capability






