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.

Create a free account to save this page, take notes and track your progress. Sign in

Searching

grep pattern file prints matching lines. Useful options:

  • -i ignore case, -v invert (non-matching lines), -n line numbers, -c count
  • -r search directories recursively, -l list matching file names
  • -E extended regular expressions (a|b, +, ?), -o print only the match
  • -w whole words, -A 2 / -B 2 lines of context after/before
Basic grep
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).

Regular expressions and recursive search
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?

  1. -n
  2. -v
  3. -x
  4. -c
Show answer

Answer: -v

Was this page helpful?