Skip to content

Linux Foundations / Find your way around Linux ยท Step 47 of 63

Lesson: Regular ExpressionsSwitch
โ† Linux Foundations

Shell and files

Regular Expressions

Describe text patterns with regular expressions and search with them using grep and sed.

A regular expression (regex) is a pattern that describes text. Instead of searching for one exact word, you can ask for "lines that start with error" or "lines that contain a digit". Tools such as grep, sed, vim and many programming languages understand them.

Make a practice file first:

bash
printf 'cat\ncot\ncart\nconcat\nct\ncoat\nCat 42\nerror: disk full\nwarning: error ignored\n' > words.txt

Literal text and the dot

Ordinary characters match themselves. A dot . matches any single character. grep prints every line where the pattern is found anywhere.

bash
$ grep 'c.t' words.txt
cat
cot
concat

cart is missing because there are two characters between c and t. Always quote the pattern so the shell does not expand it.

Anchors

^ means the start of the line and $ means the end.

bash
$ grep '^error' words.txt
error: disk full
$ grep 'at$' words.txt
cat
concat
coat

Character classes

Square brackets match one character from a set. [ao] is a or o, [0-9] is any digit, and [^0-9] is any character that is not a digit.

bash
$ grep '^c[ao]t$' words.txt
cat
cot

Repetition

* means "zero or more of the item before it".

bash
$ grep 'co*t' words.txt
cot
ct

ct matches because zero o characters is allowed. Note that this is different from the shell, where * on its own stands for any text in a filename.

Basic and extended syntax

grep and sed use basic regular expressions by default. With -E you get extended ones, where + (one or more), ? (zero or one), | (either side), () (grouping) and {2} (exact count) work without backslashes.

bash
$ grep -E 'co+t|cart' words.txt
cot
cart
$ grep -E '[0-9]{2}' words.txt
Cat 42

In basic mode a plain + is just a plus sign. GNU tools also accept \+, \? and \| in basic mode, but other systems may not.

sed can use a pattern to replace text. Parentheses capture a match, and \1 puts it back:

bash
$ echo 'Cat 42' | sed -E 's/([0-9]+)/<\1>/'
Cat <42>

For a live shell to practise in, there is the streams and text lab. The full rules are in the GNU grep manual.

Try it

  1. Create words.txt with the command above.
  2. Find lines that begin with a lowercase or uppercase C using grep '^[cC]' words.txt.
  3. Run grep -i '^cat' words.txt and compare. -i ignores case.
  4. Write a pattern that matches only ct and coat, then check it against grep -E '^c(oa)?t$' words.txt.

Check your understanding

Regular Expressions

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.