Linux and Bash course menu
Linux grep Command with Examples
Search text with grep: ignore case, count matches, show line numbers and context, search folders recursively, and use regular expressions with grep -E.
On this page
grep prints the lines that match a pattern. It is how you find one error in a log with a million lines.
Basic search#
grep ERROR app.log2026-11-05 09:04 ERROR Payment failed for order 1042
2026-11-05 09:06 ERROR Database timeoutThe search is case-sensitive, so grep info and grep INFO find different lines.
Common options#
grep -ic info app.log
grep -n WARN app.log
grep -v INFO app.log5
3:2026-11-05 09:02 WARN Disk 80 percent full
2026-11-05 09:02 WARN Disk 80 percent full
2026-11-05 09:03 info user ravi logged in
2026-11-05 09:04 ERROR Payment failed for order 1042
2026-11-05 09:06 ERROR Database timeoutContext around a match#
Often the line before a failure explains it:
grep -B 1 "Database" app.log2026-11-05 09:05 INFO Report created
2026-11-05 09:06 ERROR Database timeoutSearch many files#
grep -r "TODO" src
grep -rl "TODO" src
grep -r --include="*.py" "TODO" srcsrc/auth.py:def login(user): pass # TODO check password
src/lib/util.js:// TODO add tests
src/auth.py
src/lib/util.js
src/auth.py:def login(user): pass # TODO check passwordRegular expressions#
grep's patterns are regular expressions. -E turns on the extended form, which is easier to read.
grep -E "WARN|ERROR" app.log
grep -E "logged (in|out)$" app.log | wc -l
grep -oE "[0-9]{4}$" app.log2026-11-05 09:02 WARN Disk 80 percent full
2026-11-05 09:04 ERROR Payment failed for order 1042
2026-11-05 09:06 ERROR Database timeout
3
1042-o prints only the matching text, not the whole line.
Use it in a pipe#
ps -e | grep -c bash
grep ERROR app.log | wc -l3
2Use it in a condition#
With -q, grep is silent, and scripts use its exit code:
if grep -q "timeout" app.log; then
echo "Found a timeout"
fiFound a timeoutCommon mistakes#
Practice#
Practice exercise
Print how many lines mention asha, then print the times (09:07 style) of all ERROR lines.
Show hint
awk '{print $2}' prints the second column, or use grep -oE.
Show solution
grep -c asha app.log
grep ERROR app.log | grep -oE "[0-9]{2}:[0-9]{2}"2
09:04
09:06Key takeaway#
Next: Finding Files with find.
Finished this lesson?