Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 25 min · revision 1

Patterns that travel: regular expressions in grep, sed and awk

Why the same pattern can match in grep, change nothing in sed and behave differently in awk: the BRE, ERE and PCRE dialects, how a match is chosen (leftmost, then longest), portable building blocks, and when a regular expression is the wrong tool.

Contentsand lesson path

What you will learn

  • Write basic and extended regular expressions and use grep -E, sed and awk to filter, extract, transform and summarise log and CSV data.

Prerequisites: Scripting Basics

01. Why it matters

You test a pattern with grep and it finds exactly the lines you want. You paste the same pattern into a sed command to rewrite those lines, and nothing changes. There is no error message. Later you paste it into awk and it matches more than you expected. Nothing is broken: each tool read the pattern by slightly different rules.

A regular expression (regex) is a small language for describing text: "a digit, then one or more letters, at the end of the line". Linux tools share the idea but not one grammar. If you know which grammar a tool uses and how a match is chosen, you can predict what a pattern will do before you run it on a 2 GB log. That matters because the usual failure is not a crash but a silent wrong answer.

This lesson builds on answering questions from an access log, where you used awk fields and sort | uniq -c. Here we look at the patterns themselves. All examples were run in a Debian 13 container with GNU grep 3.11, GNU sed 4.9, gawk 5.2.1 and bash 5.2. Every block sets LC_ALL=C; the section on character classes shows why.

02. One idea, three dialects

POSIX, the standard that most Unix tools follow, defines two regex grammars. Basic regular expressions (BRE) are the older one. In a BRE, the characters +, ?, |, {, }, ( and ) are ordinary characters; to get their special meaning you write \{2\} for "exactly two" and \(…\) for a group. Extended regular expressions (ERE) turn those characters into operators without backslashes. A third family, PCRE (Perl-compatible), adds shortcuts such as \d for a digit and lazy quantifiers.

Each tool picks a default:

  • grep uses BRE; grep -E uses ERE; GNU grep -P uses PCRE.
  • sed uses BRE; sed -E uses ERE. There is no PCRE mode.
  • awk always uses ERE, in /…/ patterns and in functions such as sub and match.

The block below asks "a 5 followed by exactly two zeros at the end of the line" in BRE and in ERE, and a looser version in awk. Read it and predict which commands print nothing before you look at the output.

Bash · the same idea in BRE, ERE and awk
export LC_ALL=C
printf 'err 500\nerr 5000\nok 200\n' > codes.txt
grep '50\{2\}$' codes.txt          # BRE: interval needs backslashes
grep -E '50{2}$' codes.txt         # ERE: braces are operators
grep '50{2}$' codes.txt; echo "rc=$?"   # BRE: {2} is literal text
sed 's/\(err\) \([0-9]*\)/\2:\1/' codes.txt    # BRE groups
sed -E 's/(err) ([0-9]*)/\2:\1/' codes.txt      # ERE groups
awk '/^err 50+$/ { print "awk:", $0 }' codes.txt
Expected output
err 500
err 500
rc=1
500:err
5000:err
ok 200
500:err
5000:err
ok 200
awk: err 500
awk: err 5000

The third grep looked for the literal characters 50{2} and found none, so it printed nothing and returned 1. That is the silent failure from the opening: the pattern was valid, it simply meant something else. The two sed lines do the same rewrite; the ERE version is easier to read, which is why most people reach for -E by habit. In awk, + needs no backslash because awk is ERE, and the looser 50+ ("a 5, then one or more zeros") also matches err 5000. A practical rule: decide on ERE, write grep -E and sed -E every time, and remember that awk is already ERE.

03. How a match is chosen: leftmost, then longest

A pattern can often match a line in several places and with several lengths. POSIX fixes the choice: the match that starts leftmost wins, and among the matches that start there, the longest wins. The standard gives the example that (wee|week)(knights|night) matches all ten characters of "weeknights". PCRE works differently: it tries the alternatives in the order written and takes the first one that succeeds.

The same rule explains greedy repetition. .* means "any characters, as many as possible", so in "…" it runs to the last quote on the line, not the next one. The fix is not a cleverer engine but a narrower character set: "[^"]*" cannot cross a quote, so it stops at the first closing one.

Bash · alternation and greed
echo 'abcd' | grep -oE 'ab|abcd'     # POSIX: longest of the leftmost
echo 'abcd' | grep -oP 'ab|abcd'     # PCRE: first alternative that works
echo 'abcd' | sed -E 's/ab|abcd/[&]/'
echo 'key="a" other="b"' | grep -oE '".*"'
echo 'key="a" other="b"' | grep -oE '"[^"]*"'
Expected output
abcd
ab
[abcd]
"a" other="b"
"a"
"b"

In sed, & in the replacement stands for the whole match, so [abcd] shows exactly what was matched. If you move a pattern from a Python or JavaScript program (PCRE-like engines) into grep -E, alternations whose branches overlap can match a different amount of text. Ask: "if two branches could start at the same place, which one does this engine prefer?"

Simplification: real engines also differ in how they report sub-groups and in speed on pathological patterns. For filtering and extracting log fields, the two rules above, leftmost-longest for POSIX tools and greedy *, explain almost every surprise.

04. Building blocks that behave the same everywhere

A few pieces work in BRE, ERE and awk alike, and they cover most log work:

  • Anchors: ^ is the start of the line, $ the end. grep -x requires the whole line to match, and grep -w requires the match to stand alone as a word.
  • Bracket expressions: [0-9], [^ ] (anything but a space) and named classes such as [[:digit:]] and [[:space:]].
  • Repetition: * everywhere; +, ? and {m,n} in ERE.

Two traps deserve a demonstration. First, \d is not part of POSIX, and grep -E '\d+' treats \d as the letter d. Debian and Ubuntu builds of GNU grep accept it silently; upstream grep 3.8 and later, as built by distributions without that Debian patch, also prints grep: warning: stray \ before d. Second, which characters count as [[:upper:]], or fall inside a range like [a-z], depends on the locale, the language and encoding settings in LANG and LC_*. A UTF-8 locale counts "É" as an upper-case letter; the plain C locale knows only ASCII.

Bash · anchors, the \d trap and locale
echo 'order 42' | grep -oE '\d+'           # not a digit class here
echo 'order 42' | grep -oE '[[:digit:]]+'
printf 'id=4\nid=42\npid=4\n' > ids.txt
grep -c 'id=4' ids.txt; grep -x 'id=4' ids.txt; grep -w 'id=4' ids.txt
printf 'Zed\nalpha\nÉcole\n' > words.txt
LC_ALL=C.UTF-8 grep -c '^[[:upper:]]' words.txt
LC_ALL=C grep -c '^[[:upper:]]' words.txt
Expected output
d
42
3
id=4
id=4
2
1

The plain grep -c counted three lines because id=4 also appears inside id=42 and pid=4. -x and -w each narrowed it to the one line meant. In scripts that must give the same answer on every machine, set LC_ALL=C for byte-wise matching and sorting, unless you really need language-aware rules. If you change [[:digit:]] to [0-9], nothing changes in the C locale; in other locales some tools have matched surprising characters inside ranges, which is why the named classes are the safer habit.

05. Filter, extract, transform: which tool for which job

Think of three verbs. Filter keeps or drops whole lines: grep -E, grep -v, or an awk pattern with no action. Extract pulls out the matching part: grep -oE prints each match on its own line, and awk's match() sets RSTART and RLENGTH, the start and length of the match. Transform rewrites text: sed 's/old/new/' (add g for every match on a line), awk's sub and gsub, and tr for single characters.

Editing a file in place deserves care. sed -i.bak writes the result back to the file and keeps the original as file.bak; GNU sed also accepts -i with no suffix, which keeps nothing. sed can also limit a command to a range of lines between two patterns, such as /^listen/,/^server/.

Bash · in-place edit with a backup, ranges, match() and gsub()
printf 'listen 8080\nserver_name a\n' > site.conf
sed -i.bak -E 's/^(listen) [0-9]+$/\1 9090/' site.conf
cat site.conf; ls -1 site.conf*
sed -n '/^listen/,/^server/p' site.conf.bak
echo 'GET /api/orders/1842?x=1' |
  awk '{ if (match($2, /[0-9]+/)) print substr($2, RSTART, RLENGTH) }'
echo 'a,b;c' | awk '{ n = gsub(/[,;]/, " "); print n, $0 }'
Expected output
listen 9090
server_name a
site.conf
site.conf.bak
listen 8080
server_name a
1842
2 a b c

Around these three sit small glue tools that you will meet in the lab: tee copies a stream to a file and passes it on, nl numbers lines, paste -sd' ' - joins lines into one, split -l cuts a file into pieces, join merges two files sorted on a common field, and xargs -0 turns a NUL-separated list into arguments, which is safe for file names with spaces.

Bash · glue tools in one minute
printf 'GET,/a\nPOST,/b\nGET,/c\n' > req.csv
tr ',' ' ' < req.csv | nl -w1 -s': '
cut -d, -f1 req.csv | paste -sd' ' -
seq 1 10 > n.txt; split -l 4 -d n.txt part-; ls -1 part-*
printf '%s\0' 'a b.log' 'c.log' | xargs -0 -n1 printf '<%s>\n'
Expected output
1: GET /a
2: POST /b
3: GET /c
GET POST GET
part-00
part-01
part-02
<a b.log>
<c.log>

06. When a regular expression is the wrong tool

Regexes describe flat, line-shaped text well. They describe nested or quoted structures badly, because a regex cannot count matching brackets or know whether a comma sits inside quotes. Concrete cases where you should stop:

  • JSON from an API or a structured log. A pattern such as "status":"[^"]*" breaks when the field order changes or a value contains an escaped quote. Use jq, covered in beyond Bash: jq, yq and porting to Python.
  • CSV with quoted fields, such as "Smith, Ann",42. cut -d, and awk -F, split inside the quotes. Use a CSV parser (Python's csv module, or mlr if your team installs it).
  • HTML or XML. Use a real parser.
  • A pattern that needs comments to be understood. If a regex grows past one line, a short awk or Python program with named steps is easier to review and test.

The fair case for regexes is strong too: for a fixed, documented log format, a one-line grep -E or awk is fast, needs no extra install and runs on every server you will log into. The judgement is about the input's structure, not about the tool being "old".

07. Check your understanding

Practice check · 3 questions

Dialects, greed and choosing the tool

Predict first, then check your reasoning against the feedback.

Q1. What does this print? echo 'GET /api/v2/items HTTP/1.1' | grep -oE '/[a-z0-9/]*/'
Q2. `grep -c '^[[:upper:]]' names.txt` prints 2 on your laptop and 1 in a CI container, on the same file. What is the most likely cause?
Q3. You must change `timeout 30` to `timeout 60` in site.conf, keep a backup, and touch no other line. Which command does that?
Practice only: not graded, not saved, not evidence.

08. Apply it

Take a log you have, or this line from an imagined mail server: 2026-11-26T09:14:03Z warn queue=outbound id=8F2A9 delay=31s to=<[email protected]>. Write three commands: a grep -E filter that keeps only warn lines whose delay is 30 seconds or more, a grep -oE extraction of every id= value, and a sed -E transform that masks the mail address as <…@example.com>. Before running each one, write down what it should print and why, then run it. These patterns feed the logreport.sh practice task of this skill.

09. Review prompt

Without looking back: explain to a colleague why a pattern can work in grep -E and silently do nothing in sed, and how POSIX chooses between two possible matches on the same line. Then name one input where you would refuse to use a regex at all, and what you would use instead.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check