grep — Search for Patterns
grep searches for text patterns inside files. One of the most used Linux commands.
Basic search
grep 'student' /etc/passwd
grep 'error' /var/log/syslog
Common flags
grep -i 'Error' file.txt # Case-insensitive
grep -n 'word' file.txt # Show line numbers
grep -c 'word' file.txt # Count matching lines
grep -v 'word' file.txt # Invert: lines that DON'T match
grep -l 'word' *.txt # List files that match
grep -r 'word' directory/ # Recursive search
grep -w 'word' file.txt # Match whole words only
Context flags
grep -A 3 'error' file.txt # 3 lines After match
grep -B 3 'error' file.txt # 3 lines Before match
grep -C 3 'error' file.txt # 3 lines Context (both)
Regular expressions
grep '^root' /etc/passwd # Lines starting with 'root'
grep 'bash$' /etc/passwd # Lines ending with 'bash'
grep '[0-9]' file.txt # Lines containing digits
grep -E 'cat|dog' file.txt # Extended regex: OR
With pipes
ps aux | grep nginx
history | grep ssh