Um momento
0x60Lesson 7 of 18

Search with grep and regular expressions

Find lines that match patterns, from exact words to precise regular expressions.

26 min 7-question quiz 2 code exercises
By the end of this lesson you can
  • 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.

OptionEffect
-iignore case
-vinvert: lines that don’t match
-nshow line numbers
-ccount matching lines
-wmatch whole words only
-oprint only the matching part
-rsearch every file under a directory
-llist the files that contain a match
-Eextended regular expressions (+, ?, |, {} without backslashes)
-Ffixed string: no special characters at all
-A 2 / -B 2 / -C 2also show 2 lines after / before / around
-qprint nothing; just succeed or fail (great in if)
grep-basics.sh
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.log
Output
reactor 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):

PatternMatchesExampleMatches in the example
.any one characterc.tcat, cot, c7t
^ / $start / end of the line^ERRORlines that begin with ERROR
[abc]one of these charactersdeck[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 timesab*cac, abc, abbbc
+1 or more times[0-9]+7, 42, 2026
?0 or 1 timecolou?rcolor, colour
{n} / {n,m}exactly n / n to m times[0-9]{3}042
a|beither sideERROR|WARNeither 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.

0 of 7 sortedScore 0/0
  • “KS-042”

  • “KS-42”

  • “ks-042”

  • “KS-0420”

  • “XKS-042”

  • “KS-999”

  • “KS-0A2”

extract.sh
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.txt
Output
KS-101
KS-204
KS-87
--
nothing to report
--
Fixed KS-101 and KS-204
nothing to report

Key takeaways

  • grep pattern file prints matching lines; -i, -v, -n, -c, -w, -o and -r cover most needs.

  • Anchors (^, $), classes ([0-9]) and repetition (*, +, {n}) make patterns precise.

  • Use grep -E for extended syntax and single quotes around patterns.

  • grep -o ... | sort -u extracts 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.

Exercise 1

Filter the alerts

+25 XP

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
script.sh
Loading editor…

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.

Exercise 2

Extract the ticket IDs

+25 XP

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
script.sh
Loading editor…

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…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: