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

OptionDescription
-iCase-insensitive search
-vInvert match (show non-matching lines)
-rRecursive search in directories
-nShow line numbers
-cCount matching lines only
-lList filenames with matches only
-wMatch whole words only
-A NShow N lines after match
-B NShow N lines before match
-C NShow N lines before and after (context)
-EExtended regex (same as egrep)

Examples

$ grep ubuntu /etc/hosts
127.0.1.1    ubuntu
$ 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:

PatternMeaning
.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 --color for 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 -a to treat binary as text, or -I to skip them

See Also

  • awk — Pattern scanning and processing
  • sed — Stream editor for filtering text
  • find — Search for files
  • less — View files with search capability

Tutorials