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:
printf 'cat\ncot\ncart\nconcat\nct\ncoat\nCat 42\nerror: disk full\nwarning: error ignored\n' > words.txtLiteral text and the dot
Ordinary characters match themselves. A dot . matches any single character. grep prints every line where the pattern is found anywhere.
$ grep 'c.t' words.txt
cat
cot
concatcart 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.
$ grep '^error' words.txt
error: disk full
$ grep 'at$' words.txt
cat
concat
coatCharacter 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.
$ grep '^c[ao]t$' words.txt
cat
cotRepetition
* means "zero or more of the item before it".
$ grep 'co*t' words.txt
cot
ctct 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.
$ grep -E 'co+t|cart' words.txt
cot
cart
$ grep -E '[0-9]{2}' words.txt
Cat 42In 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:
$ 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
- Create
words.txtwith the command above. - Find lines that begin with a lowercase or uppercase C using
grep '^[cC]' words.txt. - Run
grep -i '^cat' words.txtand compare.-iignores case. - Write a pattern that matches only
ctandcoat, then check it againstgrep -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.