Search with grep and regular expressions
Find lines that match patterns, from exact words to precise regular expressions.
- Search files and streams with grep and its most useful options
- Write regular expressions with anchors, character classes and repetition
- Extract just the matching text with grep -o
grep prints the lines that match a pattern. Its name comes from an old editor command, g/re/p: globally search for a regular expression and print. It’s the tool you’ll use most when hunting through logs.
| Option | Effect |
|---|---|
-i | ignore case |
-v | invert: lines that don’t match |
-n | show line numbers |
-c | count matching lines |
-w | match whole words only |
-o | print only the matching part |
-r | search every file under a directory |
-l | list the files that contain a match |
-E | extended regular expressions (+, ?, |, {} without backslashes) |
-F | fixed string: no special characters at all |
-A 2 / -B 2 / -C 2 | also show 2 lines after / before / around |
-q | print nothing; just succeed or fail (great in if) |
1cat > ops.log <<'EOF'
2Reactor online
3reactor temperature high
4Coolant pump ERROR
5Galley coffee ready
6reactor-2 offline
7EOF
8grep reactor ops.log
9echo "--"
10grep -in reactor ops.log
11echo "--"
12grep -c -i reactor ops.log
13echo "--"
14grep -w -i reactor ops.logreactor temperature high reactor-2 offline -- 1:Reactor online 2:reactor temperature high 5:reactor-2 offline -- 3 -- Reactor online reactor temperature high reactor-2 offline
-w still matched reactor-2 because a dash isn’t a “word” character - only letters, digits and underscores are. Always single-quote patterns that contain special characters, so the shell passes them to grep untouched.
Regular expressions
A regular expression (regex) is a pattern language. Most characters match themselves; these are special (shown in the extended syntax you get with grep -E):
| Pattern | Matches | Example | Matches in the example |
|---|---|---|---|
. | any one character | c.t | cat, cot, c7t |
^ / $ | start / end of the line | ^ERROR | lines that begin with ERROR |
[abc] | one of these characters | deck[123] | deck1, deck2, deck3 |
[0-9] / [a-z] | a range | [0-9][0-9] | any two digits |
[^0-9] | anything except these | [^ ] | a non-space character |
* | the previous item 0 or more times | ab*c | ac, abc, abbbc |
+ | 1 or more times | [0-9]+ | 7, 42, 2026 |
? | 0 or 1 time | colou?r | color, colour |
{n} / {n,m} | exactly n / n to m times | [0-9]{3} | 042 |
a|b | either side | ERROR|WARN | either word |
( ) | group | (ab)+ | ab, abab |
\. | a literal dot (escape a special character) | \.log$ | names ending in .log |
Without -E, grep uses basic syntax, where +, ?, |, { and ( need a backslash to be special. Most people just reach for grep -E.
Try it
Will it match?
Station hull panels are labeled like KS-042. The inspector searches with grep -E '^KS-[0-9]{3}$'. Decide which labels it finds.
“KS-042”
“KS-42”
“ks-042”
“KS-0420”
“XKS-042”
“KS-999”
“KS-0A2”
1cat > tickets.txt <<'EOF'
2KS-101 coolant leak, see also KS-87
3Fixed KS-101 and KS-204
4nothing to report
5EOF
6grep -oE 'KS-[0-9]+' tickets.txt | sort -u
7echo "--"
8grep -vE 'KS-[0-9]+' tickets.txt
9echo "--"
10grep -E '^(Fixed|nothing)' tickets.txtKS-101 KS-204 KS-87 -- nothing to report -- Fixed KS-101 and KS-204 nothing to report
Key takeaways
grep pattern fileprints matching lines;-i,-v,-n,-c,-w,-oand-rcover most needs.Anchors (
^,$), classes ([0-9]) and repetition (*,+,{n}) make patterns precise.Use
grep -Efor extended syntax and single quotes around patterns.grep -o ... | sort -uextracts a unique list of anything that matches.
Lesson quiz
7 questions · pass with 5 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Bash scripts
Write a script in the editor and run it for real against sample input. Each run gets a fresh Linux sandbox with Bash 5.2 and the GNU tools on Wandbox, a free public service - so experiment freely, even with rm. Your script and test input are sent there.
Filter the alerts
stdin is a station log. Print every line whose level is ERROR or WARN, prefixed with its line number (grep -n style). The level is always the second word, in capitals.
- Morning log
- Quiet log
Your script runs with Bash 5.2 and GNU tools on Wandbox, a free public service, in a fresh sandbox each time. Your script and test input are sent to that service.
Extract the ticket IDs
stdin is a pile of maintenance notes that mention tickets like KS-101: the letters KS, a dash and one or more digits. Print every distinct ticket ID, one per line, sorted.
- Notes
- One ticket
Your script runs with Bash 5.2 and GNU tools on Wandbox, a free public service, in a fresh sandbox each time. Your script and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…