Cheat Sheet #day43 - grep

grep Cheatsheet
Basic Usage
Search for a Pattern in a File
grep 'pattern' filenameSearch for a Pattern in Multiple Files
grep 'pattern' file1 file2 file3
Common Options
Ignore Case Sensitivity
grep -i 'pattern' filenameShow Line Numbers
grep -n 'pattern' filenameSearch Recursively in Directories
grep -r 'pattern' directoryShow Only Matching Part of the Line
grep -o 'pattern' filenameCount the Number of Matches
grep -c 'pattern' filenameShow Lines that Do Not Match the Pattern
grep -v 'pattern' filename
Advanced Options
Search for Whole Words
grep -w 'pattern' filenameMatch the Pattern at the Beginning of a Line
grep '^pattern' filenameMatch the Pattern at the End of a Line
grep 'pattern$' filenameShow N Lines of Context Before the Match
grep -B N 'pattern' filenameShow N Lines of Context After the Match
grep -A N 'pattern' filenameShow N Lines of Context Around the Match
grep -C N 'pattern' filename
Useful Tips
Use Extended Regular Expressions
grep -E 'pattern' filenameUse Fixed Strings (Faster for Simple Strings)
grep -F 'pattern' filenameShow Only the Names of Files with Matches
grep -l 'pattern' filenameShow Only the Names of Files without Matches
grep -L 'pattern' filenameDisplay Help for
grepgrep --helpSearch Using Perl-Compatible Regular Expressions
grep -P 'pattern' filenameColorize the Output
grep --color=auto 'pattern' filename
Examples
Search for a Case-Insensitive Pattern in a File
grep -i 'error' logfile.txtSearch for a Pattern in All Files in the Current Directory
grep 'TODO' *Search for a Pattern Recursively in a Directory
grep -r 'TODO' /path/to/directorySearch for a Whole Word Only
grep -w 'hello' filenameSearch for a Pattern and Show Line Numbers
grep -n 'main' script.pySearch for a Pattern and Show Only Matching Part of the Line
grep -o 'http[s]*://[^ ]*' filenameCount the Number of Occurrences of a Pattern
grep -c 'main' script.pySearch for a Pattern and Show 3 Lines of Context After the Match
grep -A 3 'function' script.pySearch for a Pattern and Show 2 Lines of Context Before the Match
grep -B 2 'error' logfile.txtSearch for a Pattern and Show 1 Line of Context Around the Match
grep -C 1 'TODO' script.pyUse Extended Regular Expressions to Search for Multiple Patterns
grep -E 'error|warning|info' logfile.txtSearch for a Pattern Using Perl-Compatible Regular Expressions
grep -P '\d{3}-\d{2}-\d{4}' filenameSearch for a Pattern in a Compressed File
zgrep 'pattern' file.gz
This cheatsheet covers essential commands and options for using grep effectively, from basic searching to advanced pattern matching and context display. Adjust the commands according to your specific requirements and environment.




