Bash Tutorial · Pipes and Text Processing · Lesson 9 of 30
Bash grep: Search Text
Find lines matching text or regular expressions with grep, recursively, with context and counts.
Searching
grep pattern file prints matching lines. Useful options:
-iignore case,-vinvert (non-matching lines),-nline numbers,-ccount-rsearch directories recursively,-llist matching file names-Eextended regular expressions (a|b,+,?),-oprint only the match-wwhole words,-A 2/-B 2lines of context after/before
cat > app.log <<'EOF'
2026-01-15 10:00:01 INFO server started
2026-01-15 10:00:05 WARN slow request /orders 1200ms
2026-01-15 10:01:12 ERROR payment failed order=42
2026-01-15 10:02:30 info cache warmed
2026-01-15 10:03:44 ERROR timeout calling stock-service
EOF
grep ERROR app.log
echo ---
grep -in info app.log
echo ---
grep -c -v ERROR app.log
Output
2026-01-15 10:01:12 ERROR payment failed order=42 2026-01-15 10:03:44 ERROR timeout calling stock-service --- 1:2026-01-15 10:00:01 INFO server started 4:2026-01-15 10:02:30 info cache warmed --- 3
Run this on your computer — see “Get Started” for setup.
Regular expressions
^ start of line, $ end, . any character, [0-9] a digit, * zero or more, + one or more (with -E).
printf 'order=42 total=19.99\norder=7 total=5.00\nrefund order=42\n' > events.txt
grep -E '^order=[0-9]+' events.txt
grep -oE 'total=[0-9]+\.[0-9]{2}' events.txt
mkdir -p src && echo 'TODO: validate input' > src/api.sh && echo 'done' > src/lib.sh
grep -rl TODO .
Output
order=42 total=19.99 order=7 total=5.00 total=19.99 total=5.00 ./src/api.sh
Run this on your computer — see “Get Started” for setup.
Test yourself
Which option makes grep print lines that do NOT match?
-n-v-x-c
Show answer
Answer: -v