Python Searching Text with grep & ripgrep
The `grep` (Global Regular Expression Print) command is the fundamental text-searching tool in Unix. It filters lines matching specified search strings or regular expressions across standard input or multi-gigabyte files with blazing speed.
"`grep` is like a laser-targeted highlighter: feed it a 500-page book and a keyword, and it instantly rips out only the exact lines containing that keyword."
Deep Dive: How It Works
Core Options: `-i` (ignore case), `-r` or `-R` (recursive directory search), `-n` (show 1-based line numbers), `-v` (invert match / show lines NOT matching), `-c` (count matching lines), `-l` (show only filenames with matches).
Context Flags: `-B <N>` (print N lines before match), `-A <N>` (print N lines after match), `-C <N>` (print N lines context surrounding match).
Exit Codes: grep exits with 0 if match found, 1 if no match found, and 2 if an error occurred.
Syntax Blueprint
grep "pattern" file.txt grep -rn "ERROR" /var/log/ grep -v "DEBUG" server.log grep -C 2 "FATAL" crash.log
Use grep with -rn for recursive directory code search and -C for surrounding line context.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Searching for strings starting with a dash (e.g. `grep "-v" file.txt`) and getting flag parsing errors.Why it happens: grep treats leading dashes as command flags.
How to fix: Use `grep -e "-v" file.txt` or `grep -- "-v" file.txt`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Count Matching Lines with grep -c
Create `/tmp/search_test.txt` with 3 lines containing "SUCCESS" and 2 lines containing "FAIL".
Use `grep -c "SUCCESS" /tmp/search_test.txt` to count the success lines.
Delete the temporary file.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.