Skip to content
Laviyx Learn

Try

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.

Beginner5 min readUpdated
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.

Terminal
grep ERROR app.log
Output
2026-11-05 09:04 ERROR Payment failed for order 1042
2026-11-05 09:06 ERROR Database timeout

The search is case-sensitive, so grep info and grep INFO find different lines.

Common options#

OptionMeaning
-iIgnore case
-cCount matching lines
-nShow line numbers
-vShow lines that do not match
-wMatch whole words only
-lPrint only file names
-rSearch folders recursively
-A 2, -B 2, -C 2Show lines after, before, or around each match
-qPrint nothing; only set the exit code
Terminal
grep -ic info app.log
grep -n WARN app.log
grep -v INFO app.log
Output
5
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 timeout

Context around a match#

Often the line before a failure explains it:

Terminal
grep -B 1 "Database" app.log
Output
2026-11-05 09:05 INFO Report created
2026-11-05 09:06 ERROR Database timeout

Search many files#

Terminal
grep -r "TODO" src
grep -rl "TODO" src
grep -r --include="*.py" "TODO" src
Output
src/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 password

Regular expressions#

grep's patterns are regular expressions. -E turns on the extended form, which is easier to read.

PatternMatches
.Any one character
^Start of the line
$End of the line
*Zero or more of the previous item
+One or more (-E)
?Zero or one (-E)
[0-9]One digit
a|ba or b (-E)
{3}Exactly three times (-E)
Terminal
grep -E "WARN|ERROR" app.log
grep -E "logged (in|out)$" app.log | wc -l
grep -oE "[0-9]{4}$" app.log
Output
2026-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#

Terminal
ps -e | grep -c bash
grep ERROR app.log | wc -l
Output
3
2

Use it in a condition#

With -q, grep is silent, and scripts use its exit code:

Terminal
if grep -q "timeout" app.log; then
  echo "Found a timeout"
fi
Output
Found a timeout

Common 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
Terminal
grep -c asha app.log
grep ERROR app.log | grep -oE "[0-9]{2}:[0-9]{2}"
Output
2
09:04
09:06

Key takeaway#

Next: Finding Files with find.

Finished this lesson?