Here’s a cheat sheet for commonly used grep
commands:
Basic Search
Search for a String in a File:
grep "search_string" filename
Search for a String in Multiple Files:
grep "search_string" file1 file2 file3
Case-Insensitive Search:
grep -i "search_string" filename
Displaying Line Numbers
Show Line Numbers with Match:
grep -n "search_string" filename
Show Only Line Numbers:
grep -n -o "search_string" filename
Inverting Match
Show Lines Not Matching:
grep -v "search_string" filename
Recursive Search
Search in All Files Under a Directory:
grep -r "search_string" directory
Displaying Context
Show Lines Before and After Match:
grep -C 2 "search_string" filename
Show Lines After Match:
grep -A 2 "search_string" filename
Show Lines Before Match:
grep -B 2 "search_string" filename
Counting Matches
Count Number of Matches:
grep -c "search_string" filename
Using Regular Expressions
Search for Lines Starting with a Pattern:
grep "^pattern" filename
Search for Lines Ending with a Pattern:
grep "pattern$" filename
Search for Whole Words:
grep -w "word" filename
Here is a detailed grep Regex Cheat Sheet.
Recursive and Case-Insensitive
Recursive Search (Case-Insensitive):
grep -ri "search_string" directory
Showing File Names
Show Only File Names with Matches:
grep -l "search_string" file1 file2 file3
Show Only File Names without Matches:
grep -L "search_string" file1 file2 file3
Using egrep
(Extended grep)
Extended Regular Expression (ERE) Search:
egrep "pattern1|pattern2" filename
Using zgrep
(gzip Compressed Files)
Search in gzip Compressed Files:
zgrep "search_string" filename.gz
This cheat sheet covers some common use cases of grep
command. For more detailed information, refer to the grep
manual (man grep
) or online documentation.