grep Command Cheat Sheet (Linux)
Basic Usage
grep "pattern" file.txt
Searches for "pattern" in file.txt and prints matching lines.
Most Useful Options
-i Case-insensitive search
-v Invert match (show lines NOT matching)
-n Show line numbers
-c Count matching lines
-r or -R Recursive search in all files in a directory
-w Match whole words only
-l Show file names that contain matches
-o Show only the matched part of the line
--color=auto Highlight matched text in color
Show Context (Surrounding Lines)
-A N Show N lines AFTER the match
-B N Show N lines BEFORE the match
-C N Show N lines BEFORE and AFTER the match
Common Use Cases
ps aux | grep java
Search running processes for "java"
tail -f /var/log/syslog | grep "ERROR"
Follow logs and filter for "ERROR"
grep "password" *.txt
Search multiple files for a keyword
grep "login" auth.log > matches.txt
Save matching lines to a file