Grep Command Cheat Sheet
Basic Usage
grep "pattern" filename
Search for "pattern" in the specified file.
grep "pattern" *
Search for "pattern" in all files in the current directory.
grep -r "pattern" /path/to/directory
Recursively search for "pattern" in all files in the specified directory.
Common Options
grep -i "pattern" filename - Case-insensitive search.
grep -v "pattern" filename - Invert match (show lines that do not contain "pattern").
grep -c "pattern" filename - Count the number of matches in the file.
grep -n "pattern" filename - Show line numbers with matches.
grep -l "pattern" * - List filenames that contain "pattern" (no output of matching lines).
grep -o "pattern" filename - Display only the matched part of the line.
Advanced Usage
grep -E "pattern1|pattern2" filename - Use extended regex to match multiple patterns.
grep -w "word" filename - Match whole words only.
grep -A 3 "pattern" filename - Show 3 lines after each match.
grep -B 3 "pattern" filename - Show 3 lines before each match.
grep -C 3 "pattern" filename - Show 3 lines before and after each match.
ps aux | grep "process" - Find a running process by name.
cat file.txt | grep "pattern" - Use grep in a pipeline to filter output.