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.
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.
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:
2026-11-24 09:14:33 ERROR [api] payment failed order_id=ORD-200009 reason=card_declinedThe everyday options
| Option | Effect | Example |
|---|---|---|
-i | ignore case | grep -i error matches error, Error, ERROR |
-v | invert: lines that do not match | grep -v DEBUG hides debug noise |
-c | count matching lines instead of printing them | grep -c ERROR app.log |
-n | show line numbers | grep -n refused app.log |
-w | whole words only | grep -w ok doesn't match "token" |
-x | the whole line must match | grep -x "port=8080" |
-o | print only the matched text | grep -o "ORD-[0-9]*" |
-m N | stop after N matches | grep -m1 ERROR finds the first one |
-q | quiet: print nothing, only set the exit code | for scripts |
--color=auto | highlight matches (usually on by default) |
Case matters
grep -c ERROR /var/log/shop/app.log
grep -ci error /var/log/shop/app.log28
46Same 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.
wc -l /etc/ssh/sshd_config
grep -Ev '^\s*(#|$)' /etc/ssh/sshd_config| Part | Meaning |
|---|---|
-E | extended regex (explained below) |
-v | print lines that do not match |
^\s*(#|$) | lines that, after optional spaces (\s*), are a comment (#) or end immediately ($, an empty line) |
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-server131 lines, of which only 7 are actual settings. This trick is invaluable when reviewing a server's configuration.
Everyday grep
Count every line that mentions an error, whatever its case.
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
grep ERROR /var/log/shop/app.log | head -3
grep -c ERROR /var/log/shop/app.log| Part | Meaning |
|---|---|
grep ERROR FILE | print the lines containing ERROR |
| head -3 | only show the first 3 of them |
-c | instead of printing the lines, count them |
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
2828 lines contain ERROR in capitals.
2. Ignore case: -i
grep -ci error /var/log/shop/app.log
grep -i error /var/log/shop/app.log | grep -v ERROR | head -2| Part | Meaning |
|---|---|
-i | ignore case: error, Error, ERROR all match |
-ci | count, ignoring case (short options combine) |
grep -v ERROR | invert: keep only lines that do not contain ERROR |
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.html46 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
grep -n "refused" /var/log/shop/app.log | head -2
grep -w "ok" /var/log/shop/app.log | head -2| Part | Meaning |
|---|---|
-n | show the line number in front of each match, useful for less +71g or an editor |
-w | match whole words only: ok matches "health check ok" but not "token" or "broken" |
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 okCount 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
grep -ci error /var/log/shop/app.log > /root/error-count.txtWhat each part does
grep -c: count matching lines instead of printing them.-iignores case, soERROR,Erroranderrorall count.- The count goes into the file instead of the screen.
Searching many files
| Option | Effect |
|---|---|
grep word file1 file2 | search several files; each match is prefixed with its file name |
grep -r word /etc/nginx | recursive: every file under a folder |
grep -R word dir | recursive, also following symlinks |
-l | print only the names of files that contain a match |
-L | print only the names of files that don't |
-h / -H | hide / always show file names |
--include="*.conf" | only search files matching a pattern |
--exclude="*.log" / --exclude-dir=.git | skip files or folders |
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.
| Option | Prints |
|---|---|
-A N | N lines after each match |
-B N | N lines before |
-C N | N lines on both sides |
grep -B 1 -A 2 "OutOfMemoryError" /var/log/shop/app.log2026-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 --.
Context around a crash
Save the out-of-memory error together with its stack trace.
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:
| Option | Shows |
|---|---|
-A N | N lines After each match |
-B N | N lines Before each match |
-C N | N lines of Context on both sides |
1. The crash and its stack trace
grep -A 2 "OutOfMemoryError" /var/log/shop/app.log2026-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 ofReport.java, called fromWorker.run. That's exactly what a developer needs to fix it. Plaingrepwould have shown only the first line, because the stack trace lines don't contain "OutOfMemoryError".
2. What happened just before?
grep -B 1 -A 2 "OutOfMemoryError" /var/log/shop/app.log2026-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.
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
grep -A 2 "OutOfMemoryError" /var/log/shop/app.log > /root/oom-context.txtWhat each part does
-A 2: also print 2 lines after each match (-Bbefore,-Cboth), which is where the stack trace and cause usually are.
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
^2026-11-24 1[4-7]:.* ERROR → ERROR lines logged between 14:00 and 17:59.
| Symbol | Meaning | Example | Matches |
|---|---|---|---|
abc | literal text | refused | "refused" anywhere in the line |
. | any single character | h.t | hat, hot, h7t |
^ | start of the line | ^# | comment lines |
$ | end of the line | ;$ | lines ending in ; |
[abc] | one character from the set | [Ee]rror | Error, error |
[a-z], [0-9] | one character from a range | v[0-9] | v1, v7 |
[^abc] | one character not in the set | [^0-9] | any non-digit |
* | the previous item 0 or more times | ab*c | ac, 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:
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:
| Class | Same as | Means |
|---|---|---|
[[: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.
Regular expressions
Find the ERROR lines logged between 14:00 and 17:59.
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:
| Symbol | Means | Example | Matches |
|---|---|---|---|
^ | start of the line | ^2026 | lines starting with 2026 |
$ | end of the line | \.com$ | lines ending in .com |
. | any single character | h.t | hat, hot, h7t |
[abc] | one of these characters | 1[4-7] | 14, 15, 16, 17 |
* | the previous item, 0 or more times | .* | anything at all |
\. | a literal dot (escaped) | example\.com | example.com only |
1. Anchors: ^ and $
grep "^ at" /var/log/shop/app.log
grep "\.com," /srv/data/customers.csv| Pattern | Meaning |
|---|---|
^ at | lines starting with four spaces and at: stack trace lines |
\.com, | a literal .com followed by a comma. Without the backslash, . would match any character. |
at com.shop.Report.build(Report.java:88)
at com.shop.Worker.run(Worker.java:41)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,KolkataThe 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:
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| Part | Meaning |
|---|---|
^ | the line must start here, so a date inside a message can't match |
2026-11-24 1 | literal text |
[4-7] | one digit from 4 to 7 |
: | the colon after the hour |
2026-11-24 14:00:42 error [worker] template not found: checkout.html
...
7Seven 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:
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.
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
grep "^2026-11-24 1[4-7]:.* ERROR " /var/log/shop/app.log > /root/afternoon-errors.txtWhat 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.
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.
| Symbol | Meaning | Example | Matches |
|---|---|---|---|
+ | the previous item 1 or more times | [0-9]+ | 7, 42, 2026 |
? | the previous item is optional | https?:// | 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|b | a or b | WARN|ERROR | either level |
( ) | group | (GET|POST) /api | GET /api or POST /api |
grep -E "took [0-9]{4}ms" /var/log/shop/app.log | head -3What it matches: "took", a space, exactly four digits, then "ms": queries that took 1,000 ms or more.
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 3431msWord 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.
grep -Eo "[a-z0-9._]+@[a-z0-9.-]+\.[a-z]+" /srv/data/customers.csv| Piece | Matches |
|---|---|
[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?":
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 11 reason=card_declined
10 reason=timeout10.0.3.7The 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.
Extract with -E and -o
Produce a sorted list of unique order IDs whose payment failed.
Extended regular expressions (grep -E) add more operators without needing backslashes:
| Symbol | Means | Example |
|---|---|---|
+ | the previous item, 1 or more times | [0-9]+ = one or more digits |
? | the previous item is optional | https? = http or https |
{n} / {n,m} | exactly n / between n and m times | [0-9]{6} = exactly 6 digits |
a|b | either a or b | WARN|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
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| Pattern | Matches |
|---|---|
WARN|ERROR | lines with WARN or ERROR |
took [0-9]{4}ms | "took" followed by exactly 4 digits: queries slower than 1 second |
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 3431ms2. Extract only what matches: -o
grep -Eo "[a-z0-9._]+@[a-z0-9.-]+\.[a-z]+" /srv/data/customers.csvWhat 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
grep -o "reason=[a-z_]*" /var/log/shop/app.log | sort | uniq -c 11 reason=card_declined
10 reason=timeoutTen 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.
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
grep "payment failed" /var/log/shop/app.log | grep -Eo "ORD-[0-9]+" | sort -u > /root/order-ids.txtsort -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]+":-Eextended regex,-oprint only the matching part:ORD-followed by one or more digits.sort -u: sort and keep each order ID once (unique).
Literal text and several patterns
| Option | Effect |
|---|---|
-F | fixed 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 PAT | give a pattern explicitly; repeat for several: grep -e refused -e timeout (lines with either) |
-f FILE | read 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 code | Meaning |
|---|---|
0 | at least one match |
1 | no match |
2 | an 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 &&:
grep -q "OutOfMemoryError" /var/log/shop/app.log && echo "crash found"
grep -q "Segfault" /var/log/shop/app.log; echo "exit code: $?"crash found
exit code: 1if ! grep -q "^maintenance=false" /etc/shopapp/shopapp.conf; then
echo "Warning: maintenance mode setting missing"
figrep on compressed files and processes
| Command | Searches |
|---|---|
zgrep ERROR app.log.3.gz | inside a gzip-compressed (rotated) log |
ps aux | grep nginx | the process list. It also matches the grep command itself; pgrep -a nginx avoids that. |
journalctl -u nginx | grep -i error | a service's logs |
history | grep docker | your 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 FILEprints matching lines. Quote your patterns.- Options:
-icase,-vinvert,-ccount,-nnumbers,-wwords,-oonly the match,-m Nstop after N,-qquiet. - Files:
-rrecursive,-lnames only,--include/--exclude. Context:-A,-B,-C. - Regex:
.any char,^start,$end,[...]sets and ranges,*repeat,\escape. -Eadds+,?,{n,m},|,( );-Padds\d,\s,\w;-Fsearches literal text.-o+sort | uniq -ccounts occurrences. Exit codes: 0 found, 1 not found, 2 error.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.