Learn / Linux / Text Processing
Lesson 11 of 74

Searching Text: grep and Regular Expressions

grep from the basics to real investigations: every everyday option, searching many files, context lines, regular expressions (anchors, classes, quantifiers, groups), extended and Perl regex, extracting matches with -o, and using grep in scripts.

30 min read Report a problem Hands-on lab included 6-question quiz

What grep does

grep reads text line by line and prints every line that matches a pattern. The name comes from an old editor command, g/re/p: globally search for a regular expression and print.

text
grep  [OPTIONS]  PATTERN  [FILE...]

It can read files, or anything piped into it: ps aux | grep nginx. It's probably the command DevOps engineers type most after ls and cd, because nearly every investigation starts with "find the lines that mention X".

All examples in this lesson use the shop's application log, where each line looks like:

text
2026-11-24 09:14:33 ERROR [api] payment failed order_id=ORD-200009 reason=card_declined

The everyday options

OptionEffectExample
-iignore casegrep -i error matches error, Error, ERROR
-vinvert: lines that do not matchgrep -v DEBUG hides debug noise
-ccount matching lines instead of printing themgrep -c ERROR app.log
-nshow line numbersgrep -n refused app.log
-wwhole words onlygrep -w ok doesn't match "token"
-xthe whole line must matchgrep -x "port=8080"
-oprint only the matched textgrep -o "ORD-[0-9]*"
-m Nstop after N matchesgrep -m1 ERROR finds the first one
-qquiet: print nothing, only set the exit codefor scripts
--color=autohighlight matches (usually on by default)

Case matters

bash
grep -c ERROR /var/log/shop/app.log
grep -ci error /var/log/shop/app.log
text
28
46

Same log, two answers. One component logs error in lowercase, so the case-sensitive count missed 18 lines. When counting problems, ask yourself whether case could differ.

Invert: filtering noise out

-v is as useful as normal matching. A classic: show a config file without comments and blank lines.

bash
wc -l /etc/ssh/sshd_config
grep -Ev '^\s*(#|$)' /etc/ssh/sshd_config
PartMeaning
-Eextended regex (explained below)
-vprint lines that do not match
^\s*(#|$)lines that, after optional spaces (\s*), are a comment (#) or end immediately ($, an empty line)
text
131 /etc/ssh/sshd_config
Include /etc/ssh/sshd_config.d/*.conf
KbdInteractiveAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem	sftp	/usr/lib/openssh/sftp-server

131 lines, of which only 7 are actual settings. This trick is invaluable when reviewing a server's configuration.

Try it · Task 1 of 4

Everyday grep

Count every line that mentions an error, whatever its case.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

grep searches line by line and is case-sensitive by default: ERROR and error are different words to it. A handful of options change what it matches and what it prints. You'll use these five every week.

1. Plain search, and counting

bash
grep ERROR /var/log/shop/app.log | head -3
grep -c ERROR /var/log/shop/app.log
PartMeaning
grep ERROR FILEprint the lines containing ERROR
| head -3only show the first 3 of them
-cinstead of printing the lines, count them
text
2026-11-24 09:14:33 ERROR [api] payment failed order_id=ORD-200009 reason=card_declined
2026-11-24 09:38:48 ERROR [worker] payment failed order_id=ORD-200024 reason=timeout
2026-11-24 10:04:40 ERROR [worker] payment failed order_id=ORD-200040 reason=card_declined
28

28 lines contain ERROR in capitals.

2. Ignore case: -i

bash
grep -ci error /var/log/shop/app.log
grep -i error /var/log/shop/app.log | grep -v ERROR | head -2
PartMeaning
-iignore case: error, Error, ERROR all match
-cicount, ignoring case (short options combine)
grep -v ERRORinvert: keep only lines that do not contain ERROR
text
46
2026-11-24 09:00:00 error [api] template not found: checkout.html
2026-11-24 09:21:01 error [worker] template not found: checkout.html

46 instead of 28. One component logs its level in lowercase (error), and a case-sensitive search silently missed those 18 lines. When counting problems, think about case.

3. Line numbers and whole words

bash
grep -n "refused" /var/log/shop/app.log | head -2
grep -w "ok" /var/log/shop/app.log | head -2
PartMeaning
-nshow the line number in front of each match, useful for less +71g or an editor
-wmatch whole words only: ok matches "health check ok" but not "token" or "broken"
text
71:2026-11-24 10:53:10 ERROR [web] database connection refused host=10.0.3.7
79:2026-11-24 11:06:06 ERROR [worker] database connection refused host=10.0.3.7
2026-11-24 09:04:51 INFO  [api] health check ok
2026-11-24 09:08:05 INFO  [web] health check ok
2 · Your task

Count how many lines in /var/log/shop/app.log contain the word error in any upper or lower case, and save just the number to /root/error-count.txt.

Expected result: cat /root/error-count.txt prints the count.

Hint: the commands, explained
text
grep -ci error /var/log/shop/app.log > /root/error-count.txt

What each part does

  • grep -c: count matching lines instead of printing them. -i ignores case, so ERROR, Error and error all count.
  • The count goes into the file instead of the screen.
First start the lab machine in the terminal panel on the right.

Searching many files

OptionEffect
grep word file1 file2search several files; each match is prefixed with its file name
grep -r word /etc/nginxrecursive: every file under a folder
grep -R word dirrecursive, also following symlinks
-lprint only the names of files that contain a match
-Lprint only the names of files that don't
-h / -Hhide / always show file names
--include="*.conf"only search files matching a pattern
--exclude="*.log" / --exclude-dir=.gitskip files or folders
text
grep -rn "proxy_pass" /etc/nginx              # where is proxy_pass configured, and on which line?
grep -rl "10.0.3.7" /etc                      # which config files mention this old IP?
grep -r --include="*.yaml" "image:" k8s/      # which images do our Kubernetes manifests use?

Context: lines around a match

A single line rarely tells the whole story. A crash is followed by a stack trace, and an error is often preceded by its cause.

OptionPrints
-A NN lines after each match
-B NN lines before
-C NN lines on both sides
bash
grep -B 1 -A 2 "OutOfMemoryError" /var/log/shop/app.log
text
2026-11-24 13:00:53 ERROR [web] database connection refused host=10.0.3.7
2026-11-24 13:02:11 ERROR [worker] java.lang.OutOfMemoryError: Java heap space
    at com.shop.Report.build(Report.java:88)
    at com.shop.Worker.run(Worker.java:41)

The line before shows what happened just earlier; the two lines after are the stack trace pointing at Report.java, line 88. When matches are far apart, grep separates each group with a line containing --.

Try it · Task 2 of 4

Context around a crash

Save the out-of-memory error together with its stack trace.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

One matching line is often not enough. A crash is usually followed by a stack trace (the lines showing where in the code it happened), and the lines before an error often show what triggered it. grep can print lines around each match:

OptionShows
-A NN lines After each match
-B NN lines Before each match
-C NN lines of Context on both sides

1. The crash and its stack trace

bash
grep -A 2 "OutOfMemoryError" /var/log/shop/app.log
text
2026-11-24 13:02:11 ERROR [worker] java.lang.OutOfMemoryError: Java heap space
    at com.shop.Report.build(Report.java:88)
    at com.shop.Worker.run(Worker.java:41)
  • Line 1: the error. The worker ran out of memory ("Java heap space").
  • Lines 2 and 3: the stack trace. The crash happened in Report.build, line 88 of Report.java, called from Worker.run. That's exactly what a developer needs to fix it. Plain grep would have shown only the first line, because the stack trace lines don't contain "OutOfMemoryError".

2. What happened just before?

bash
grep -B 1 -A 2 "OutOfMemoryError" /var/log/shop/app.log
text
2026-11-24 13:00:53 ERROR [web] database connection refused host=10.0.3.7
2026-11-24 13:02:11 ERROR [worker] java.lang.OutOfMemoryError: Java heap space
    at com.shop.Report.build(Report.java:88)
    at com.shop.Worker.run(Worker.java:41)

A minute before the crash, the database refused a connection. Related or not, it's the kind of clue context gives you. When several matches are close together, grep separates the groups with a -- line.

2 · Your task

Save the OutOfMemoryError line and the 2 stack-trace lines that follow it (exactly those 3 lines) to /root/oom-context.txt.

Expected result: /root/oom-context.txt contains 3 lines: the error and its two at ... lines.

Hint: the commands, explained
text
grep -A 2 "OutOfMemoryError" /var/log/shop/app.log > /root/oom-context.txt

What each part does

  • -A 2: also print 2 lines after each match (-B before, -C both), which is where the stack trace and cause usually are.
First start the lab machine in the terminal panel on the right.

Regular expressions

So far the patterns were plain words. grep's patterns are actually regular expressions (regex): a compact language for describing text. The same language is used in sed, awk, vim, Python, JavaScript, nginx location blocks, Prometheus queries and log tools, so it pays off far beyond grep.

The building blocks

Reading a regular expression

^start of line
2026-11-24 1literal text
[4-7]one character from 4 to 7
:literal
.*any characters, any number of times
␣ERROR␣literal, with spaces

^2026-11-24 1[4-7]:.* ERROR → ERROR lines logged between 14:00 and 17:59.

SymbolMeaningExampleMatches
abcliteral textrefused"refused" anywhere in the line
.any single characterh.that, hot, h7t
^start of the line^#comment lines
$end of the line;$lines ending in ;
[abc]one character from the set[Ee]rrorError, error
[a-z], [0-9]one character from a rangev[0-9]v1, v7
[^abc]one character not in the set[^0-9]any non-digit
*the previous item 0 or more timesab*cac, abc, abbbc
\escape: make the next character literal\. \[ \$a real dot, bracket, dollar

Anchors make patterns precise

Without anchors, a pattern matches anywhere in the line. ERROR would also match a message that merely mentions "ERROR". Anchors pin it down:

text
grep "^2026-11-24 14:" app.log      # lines that START with that time, not ones that mention it
grep "\.conf$" file-list.txt        # lines that END in .conf
grep "^$" file.txt                  # empty lines
grep -c "^" file.txt                # every line (counts lines, like wc -l)

The dot is not a dot

The most common regex bug: . means "any character". grep "10.0.3.7" also matches 10x0y3z7. Usually harmless, but to be exact, escape it: grep "10\.0\.3\.7", or use grep -F (below) to search for literal text.

Character classes

Named classes are clearer than ranges and work in any language:

ClassSame asMeans
[[:digit:]][0-9]a digit
[[:alpha:]][a-zA-Z]a letter
[[:alnum:]][a-zA-Z0-9]a letter or digit
[[:space:]]space, tab, newline
[[:upper:]] / [[:lower:]]upper / lower case letter

Note the double brackets: [:digit:] is the class name, and it goes inside a normal [ ] set.

Try it · Task 3 of 4

Regular expressions

Find the ERROR lines logged between 14:00 and 17:59.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

So far the patterns were plain words. grep's patterns are actually regular expressions (regex): a small language for describing text. A few special characters go a long way:

SymbolMeansExampleMatches
^start of the line^2026lines starting with 2026
$end of the line\.com$lines ending in .com
.any single characterh.that, hot, h7t
[abc]one of these characters1[4-7]14, 15, 16, 17
*the previous item, 0 or more times.*anything at all
\.a literal dot (escaped)example\.comexample.com only

1. Anchors: ^ and $

bash
grep "^    at" /var/log/shop/app.log
grep "\.com," /srv/data/customers.csv
PatternMeaning
^ atlines starting with four spaces and at: stack trace lines
\.com,a literal .com followed by a comma. Without the backslash, . would match any character.
text
    at com.shop.Report.build(Report.java:88)
    at com.shop.Worker.run(Worker.java:41)
text
1,Asha Rao,[email protected],+91-98450-11111,Bengaluru
3,Meera Iyer,[email protected],,Chennai
4,Rahul Das,rahul.das(at)example.com,+91-90000-33333,Kolkata

The second search found Rahul's line too: his "email" ends in .com, but it isn't a valid address. A pattern only checks what you tell it to check.

2. Ranges: lines from a time window

The time is at a fixed position at the start of each line. ^2026-11-24 1[4-7]: matches lines whose hour is 14, 15, 16 or 17:

bash
grep "^2026-11-24 1[4-7]:" /var/log/shop/app.log | head -3
grep "^2026-11-24 1[4-7]:" /var/log/shop/app.log | grep -c ERROR
PartMeaning
^the line must start here, so a date inside a message can't match
2026-11-24 1literal text
[4-7]one digit from 4 to 7
:the colon after the hour
text
2026-11-24 14:00:42 error [worker] template not found: checkout.html
...
7

Seven errors in the afternoon window (14:00 to 17:59).

3. ".*" means "anything in between"

You can do it in a single grep: date and hour at the start, then anything, then ERROR:

text
grep "^2026-11-24 1[4-7]:.* ERROR " /var/log/shop/app.log

.* matches any characters, any number of times. The spaces around ERROR make sure it's the level column, not part of a word.

2 · Your task

Save every ERROR line (uppercase level) logged between 14:00 and 17:59 to /root/afternoon-errors.txt.

Expected result: /root/afternoon-errors.txt contains only ERROR lines, all with hours 14 to 17.

Hint: the commands, explained
text
grep "^2026-11-24 1[4-7]:.* ERROR " /var/log/shop/app.log > /root/afternoon-errors.txt

What each part does

  • ^2026-11-24 1[4-7]:: lines that start (^) with the date and an hour from 14 to 17 ([4-7] matches one digit 4, 5, 6 or 7).
  • .* ERROR : then anything (.*), then the word ERROR with spaces around it.
First start the lab machine in the terminal panel on the right.

Extended regular expressions: grep -E

Basic grep treats +, ?, { }, | and ( ) as plain characters unless you put a backslash in front. grep -E (extended regex, also available as egrep) makes them special, which is easier to read. Most people simply always use -E.

SymbolMeaningExampleMatches
+the previous item 1 or more times[0-9]+7, 42, 2026
?the previous item is optionalhttps?://http:// or https://
{n}exactly n times[0-9]{4}a 4-digit number
{n,m}between n and m times[0-9]{1,3}1 to 3 digits
a|ba or bWARN|ERROReither level
( )group(GET|POST) /apiGET /api or POST /api
bash
grep -E "took [0-9]{4}ms" /var/log/shop/app.log | head -3

What it matches: "took", a space, exactly four digits, then "ms": queries that took 1,000 ms or more.

text
2026-11-24 09:01:37 WARN  [web] slow query took 3183ms
2026-11-24 09:29:06 WARN  [web] slow query took 2559ms
2026-11-24 10:17:36 WARN  [worker] slow query took 3431ms

Word boundaries \b match the edge of a word: grep -E "\bok\b" finds "ok" as a word, like -w.

Perl regex (grep -P) adds shortcuts from programming languages: \d (digit), \s (whitespace), \w (word character), and more. grep -P "\d{3}ms" means the same as grep -E "[0-9]{3}ms". Handy if you already know regex from Python or JavaScript.

Extracting text: -o

-o prints only the part of the line that matched, each match on its own line. That turns grep from a filter into an extraction tool.

bash
grep -Eo "[a-z0-9._]+@[a-z0-9.-]+\.[a-z]+" /srv/data/customers.csv
PieceMatches
[a-z0-9._]+the name part: letters, digits, dots, underscores
@the at sign
[a-z0-9.-]+the domain
\.[a-z]+a dot and the ending (.com, .in, .org)

Only the emails, not the whole CSV lines. (This is a practical pattern, not a perfect email validator.)

Combined with sort and uniq -c, -o answers "how many of each?":

bash
grep -o "reason=[a-z_]*" /var/log/shop/app.log | sort | uniq -c
grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/log/shop/app.log | sort -u
text
     11 reason=card_declined
     10 reason=timeout
text
10.0.3.7

The failure reasons with counts, and every IP address mentioned in the log (here just the database server). The IP pattern reads: one to three digits and a dot, three times, then one to three digits.

Try it · Task 4 of 4

Extract with -E and -o

Produce a sorted list of unique order IDs whose payment failed.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Extended regular expressions (grep -E) add more operators without needing backslashes:

SymbolMeansExample
+the previous item, 1 or more times[0-9]+ = one or more digits
?the previous item is optionalhttps? = http or https
{n} / {n,m}exactly n / between n and m times[0-9]{6} = exactly 6 digits
a|beither a or bWARN|ERROR
( )group(GET|POST) /api

And -o prints only the matched text instead of the whole line. Together they turn grep into an extraction tool.

1. Either one or the other

bash
grep -E "WARN|ERROR" /var/log/shop/app.log | wc -l
grep -E "took [0-9]{4}ms" /var/log/shop/app.log | head -3
PatternMatches
WARN|ERRORlines with WARN or ERROR
took [0-9]{4}ms"took" followed by exactly 4 digits: queries slower than 1 second
text
74
2026-11-24 09:01:37 WARN  [web] slow query took 3183ms
2026-11-24 09:29:06 WARN  [web] slow query took 2559ms
2026-11-24 10:17:36 WARN  [worker] slow query took 3431ms

2. Extract only what matches: -o

bash
grep -Eo "[a-z0-9._]+@[a-z0-9.-]+\.[a-z]+" /srv/data/customers.csv

What it does: finds email-like text (letters, digits, dots or underscores, then @, then a domain, a dot and a suffix) and prints only the email, not the whole CSV line.

Four valid emails. rahul.das(at)example.com and "not provided" don't match the pattern, so they're left out: a quick data-quality check.

3. Count reasons with -o

bash
grep -o "reason=[a-z_]*" /var/log/shop/app.log | sort | uniq -c
text
     11 reason=card_declined
     10 reason=timeout

Ten payments failed with a timeout: that's the shop's problem, not the customers' cards. A grep, a sort and a count turned 300 lines into a decision.

2 · Your task

Create /root/order-ids.txt: the unique order IDs (like ORD-200024) of all lines containing payment failed, sorted, one per line.

Expected result: a sorted list of order IDs, no duplicates, nothing else on the lines.

Hint: the commands, explained
text
grep "payment failed" /var/log/shop/app.log | grep -Eo "ORD-[0-9]+" | sort -u > /root/order-ids.txt

sort -u sorts and removes duplicates in one step.

What each part does

  • grep "payment failed": keep only the failure lines.
  • grep -Eo "ORD-[0-9]+": -E extended regex, -o print only the matching part: ORD- followed by one or more digits.
  • sort -u: sort and keep each order ID once (unique).
First start the lab machine in the terminal panel on the right.

Literal text and several patterns

OptionEffect
-Ffixed string: no regex at all. grep -F "[web]" searches for the literal text [web] (as a regex, [web] would mean "w, e or b"). Also faster.
-e PATgive a pattern explicitly; repeat for several: grep -e refused -e timeout (lines with either)
-f FILEread patterns from a file, one per line: grep -f blocked-ips.txt access.log

grep in scripts: exit codes and -q

grep's exit code tells you whether it found something:

Exit codeMeaning
0at least one match
1no match
2an error (for example, the file doesn't exist)

-q (quiet) prints nothing and stops at the first match, which makes it perfect for if statements and &&:

bash
grep -q "OutOfMemoryError" /var/log/shop/app.log && echo "crash found"
grep -q "Segfault" /var/log/shop/app.log; echo "exit code: $?"
text
crash found
exit code: 1
bash
if ! grep -q "^maintenance=false" /etc/shopapp/shopapp.conf; then
  echo "Warning: maintenance mode setting missing"
fi

grep on compressed files and processes

CommandSearches
zgrep ERROR app.log.3.gzinside a gzip-compressed (rotated) log
ps aux | grep nginxthe process list. It also matches the grep command itself; pgrep -a nginx avoids that.
journalctl -u nginx | grep -i errora service's logs
history | grep dockeryour own command history

Forgetting to quote patterns. grep ERROR|WARN app.log is split by the shell into grep ERROR piped into a command called WARN. And grep *.conf gets expanded by the shell into file names. Always put patterns in quotes, and prefer single quotes for regex so the shell leaves $ and \ alone: grep -E 'WARN|ERROR' app.log.

"How do you find all lines containing ERROR in all logs under /var/log, with line numbers?" grep -rn "ERROR" /var/log (add -i for any case, --include="*.log" to limit file types).

"How do you show a config file without comments and blank lines?" grep -Ev '^\s*(#|$)' file.

"How do you count unique IPs in an access log?" grep -Eo '^[0-9.]+' access.log | sort -u | wc -l, or with cut/awk taking the first field.

"What's the difference between grep, grep -E and grep -F?" Basic regex, extended regex (+ ? {} | () without backslashes), and fixed strings with no regex at all.

Summary

  • grep PATTERN FILE prints matching lines. Quote your patterns.
  • Options: -i case, -v invert, -c count, -n numbers, -w words, -o only the match, -m N stop after N, -q quiet.
  • Files: -r recursive, -l names only, --include/--exclude. Context: -A, -B, -C.
  • Regex: . any char, ^ start, $ end, [...] sets and ranges, * repeat, \ escape.
  • -E adds +, ?, {n,m}, |, ( ); -P adds \d, \s, \w; -F searches literal text.
  • -o + sort | uniq -c counts occurrences. Exit codes: 0 found, 1 not found, 2 error.
Check your understanding

Quick quiz

Feedback