The real question is often which file contains a particular piece of text. grep reads text and returns lines matching a pattern, making it useful for logs, configuration, and source code.
Basic matching and case
grep "error" app.log prints lines containing lowercase error. Matching is case-sensitive by default; grep -i "error" app.log also matches Error and ERROR. -n adds line numbers, as in grep -n "timeout" app.log.
Reduce noise or widen scope
-v inverts the match, so grep -v "DEBUG" app.log excludes DEBUG lines. -r searches a directory recursively; grep -rn "database_url" . includes paths and line numbers. Use -l when only matching filenames matter.
-iignore case
-nshow line numbers
-vinvert the match
-rsearch recursively
-llist filenames only
-wmatch whole words
-ccount matching lines
^ / $line start / end
Whole words, regular expressions, and counts
grep -w "cat" animals.txt matches the complete word cat without treating category as equivalent. ^ERROR matches only lines beginning with ERROR, and failed$ only lines ending in failed. When only the quantity matters, grep -c "ERROR" app.log returns the matching line count.
Combined options: grep -ril "TODO" . ignores case, searches recursively, and prints each matching file path once.
Log Highlight Search
INFO server started on port 8080DEBUG cache warmup completeERROR database connection timeoutINFO catalog contains cat and dogWARN catch block retried requesterror payment gateway unavailableERROR disk usage above thresholdgrep -in "error" app.logKNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Locate Production Configuration and Errors
Write four grep commands in the current project for the investigations below.
- Recursively search for api_key, ignoring case, with files and line numbers.
- List only file paths containing the whole word TODO.
- Show lines in app.log that do not contain DEBUG.
- Count log lines beginning with ERROR.