SyntaxStudy
Sign Up
Linux / Bash Beginner 1 min read

Searching Text with grep

The `grep` command searches for patterns in text. It scans files line by line and prints each line that matches the given regular expression or fixed string. It is one of the most versatile and widely used tools in the Linux toolkit, essential for log analysis, code searching, and data filtering. Key options include `-i` for case-insensitive matching, `-r` for recursive directory search, `-n` to show line numbers, `-v` to invert the match (print non-matching lines), `-c` to count matches, and `-l` to list only filenames containing matches. The `-E` flag enables extended regular expressions (ERE) allowing alternation and quantifiers without escaping. The related commands `egrep` (equivalent to `grep -E`) and `fgrep` (fixed strings, no regex) are available on most systems. For very large files or code repositories, `ripgrep` (`rg`) is a modern, faster alternative that respects `.gitignore` by default. Understanding grep is foundational because many other tools pipe their output to it.
Example
# Basic pattern search
grep "error" /var/log/syslog

# Case-insensitive search
grep -i "error" /var/log/syslog

# Show line numbers
grep -n "failed" /var/log/auth.log

# Invert match — lines NOT containing pattern
grep -v "^#" /etc/ssh/sshd_config   # Show non-comment lines

# Count matching lines
grep -c "GET" /var/log/nginx/access.log

# List only filenames that contain a match
grep -rl "password" /etc/

# Recursive search with context (2 lines before and after)
grep -rn -C 2 "TODO" /var/www/html/

# Extended regex — match multiple patterns
grep -E "error|warning|critical" /var/log/syslog

# Match whole words only
grep -w "root" /etc/passwd

# Fixed string search (no regex, faster)
grep -F "192.168.1.1" /var/log/nginx/access.log

# Show only the matched portion, not the whole line
grep -o "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" /var/log/nginx/access.log | sort | uniq -c | sort -rn

# Exclude binary files
grep -I "pattern" /usr/bin/*

# Search with colour highlighting
grep --color=auto "FAILED" /var/log/auth.log