Regex basics
On this page
You search for error and get both a complete status word and a filename containing that word. The search found the letters you requested, but your question was narrower: which line contains exactly that status?
By the end, you can express that boundary, select a digit, repeat a character, and match a literal dot. You can also explain why copying a shell wildcard into grep changes its meaning.
Before you start
Section titled “Before you start”Finish Searching inside files (B10.2). Keep your B04 lab directory. Prepare these fixed sample lines and empty files only in ~/lab/b10/regex:
mkdir -p ~/lab/b10/regexcd ~/lab/b10/regexprintf 'error\nerrors\nerror7\nerror.log\nerro\nwarning\n' > samples.txttouch error.txt errors.txt erro.txt warning.txtThe text file is the input for every regex example. The empty files exist only for the shell-glob comparison. Use Reset this lesson before repeating the setup.
cat -n samples.txt 1 error 2 errors 3 error7 4 error.log 5 erro 6 warningcat -n numbers all input lines for inspection. The searches below use grep -n to identify selected source lines, as in B10.2. Neither command writes those number prefixes into samples.txt.
Require a start or a whole line
Section titled “Require a start or a whole line”A regular expression, or regex, describes text to match. These examples use grep’s default basic regular expressions. No -E or other regex mode is needed for the operators taught here.
Start with a boundary:
grep -n '^error' samples.txt1:error2:errors3:error74:error.log^ anchors the match to the start of a line. It matches a position, not a printed character. Text may still follow error, so the suffixed entries are selected too.
Predict first: which of those lines will remain if you also require the line to end after error?
grep -n '^error$' samples.txtRun it, then compare with your guess
1:errorOnly the first line remains. $ anchors the end. With both anchors, the pattern accepts exactly error, without additional characters before or after it.
learner@rootvolt:~/lab/b10/regex$ grep -n '^error' samples.txt1:error
2:errors
3:error7
4:error.loglearner@rootvolt:~/lab/b10/regex$ grep -n '^error$' samples.txt1:errorlearner@rootvolt:~/lab/b10/regex$ Steps (6)
- Type
grep -n '^error' samples.txt - Press Enter
- Output:
1:error 2:errors 3:error7 4:error.log - Type
grep -n '^error$' samples.txt - Press Enter
- Output:
1:error
An unanchored regex can match a portion of a line. A whole line is printed once it contains a match; the printed line and the matched portion need not have the same length.
Select one character or repeat the previous one
Section titled “Select one character or repeat the previous one”grep -n '[0-9]' samples.txt3:error7The bracket expression [0-9] selects one digit in the tested lab locale. A character class describes a set of possible characters at one position. Here the only selected line contains 7. The pattern does not require the whole line to be a single digit because it has no anchors.
The named class [[:digit:]] is another way to request a digit. Bracket ranges and character classes can depend on locale; these examples are verified under the course’s en_US.UTF-8 locale.
Now repeat a particular character:
grep -n '^errors*$' samples.txt1:error2:errors* means zero or more repetitions of the preceding item. Here that item is s, so both error and errors match. The error line uses zero repetitions. The anchors reject the extra digit and dot suffixes. This pattern would also accept more trailing s characters; this fixture contains only the two shown cases.
learner@rootvolt:~/lab/b10/regex$ grep -n '[0-9]' samples.txt3:error7learner@rootvolt:~/lab/b10/regex$ grep -n '^errors*$' samples.txt1:error
2:errorslearner@rootvolt:~/lab/b10/regex$ Steps (6)
- Type
grep -n '[0-9]' samples.txt - Press Enter
- Output:
3:error7 - Type
grep -n '^errors*$' samples.txt - Press Enter
- Output:
1:error 2:errors
Do not read * as a freestanding instruction to accept anything. It modifies the item immediately before it. A dot, ., is a regex item that matches any one character in these ordinary lines; .* therefore allows zero or more such characters.
Match punctuation literally
Section titled “Match punctuation literally”A regex dot has a special meaning. To require the actual dot in error.log, put a backslash before it:
grep -n '^error\.log$' samples.txt4:error.logSingle quotes preserve the backslash for grep. Bash removes the quote characters; grep receives the regex containing \. and interprets that pair as a literal dot. Without the backslash, the dot position could accept a different character.
learner@rootvolt:~/lab/b10/regex$ grep -n '^error\.log$' samples.txt4:error.loglearner@rootvolt:~/lab/b10/regex$ Steps (3)
- Type
grep -n '^error\.log$' samples.txt - Press Enter
- Output:
4:error.log
In words: require the start, match error, require one literal dot, match log, then require the end. The quotes used at the shell prompt protect this regex; they are not part of it.
Keep regex separate from shell globbing
Section titled “Keep regex separate from shell globbing”Predict first: in a regex, does error* mean “the word error followed by anything,” as it would in a filename glob?
printf '%s\n' error*grep -n 'error*' samples.txtRun it, then compare with your guess
errors.txterror.txt1:error2:errors3:error74:error.log5:erroNo. Bash expands the unquoted glob into existing filenames beginning with error. In the quoted regex, * repeats the final r. The line erro matches with zero copies of that r. Unanchored matching also accepts a matching portion of the longer lines.
learner@rootvolt:~/lab/b10/regex$ printf '%s\n' error*errors.txt
error.txtlearner@rootvolt:~/lab/b10/regex$ grep -n 'error*' samples.txt1:error
2:errors
3:error7
4:error.log
5:errolearner@rootvolt:~/lab/b10/regex$ Steps (6)
- Type
printf '%s\n' error* - Press Enter
- Output:
errors.txt error.txt - Type
grep -n 'error*' samples.txt - Press Enter
- Output:
1:error 2:errors 3:error7 4:error.log 5:erro
The same symbol belongs to different pattern languages. A quoted find -name 'error*' uses a filename glob interpreted by find. A quoted grep 'error*' samples.txt uses a regex interpreted by grep. Quotes protect the argument from Bash; they do not choose the pattern language for the receiving command.
Check every fixed line
Section titled “Check every fixed line”The following tables cover every line for the seven recorded valid searches, including the challenge, one table per pattern. Match rows correspond exactly to source line numbers printed in the capture; no-match rows are the remaining lines of the same inspected file. These static tables and the verified replays replace an interactive matcher; the page does not execute a pattern you type.
Pattern ^error
| Sample line | Result |
|---|---|
1: error |
Match. Starts with error. |
2: errors |
Match. Starts with error. |
3: error7 |
Match. Starts with error. |
4: error.log |
Match. Starts with error. |
5: erro |
No match. The final r is missing. |
6: warning |
No match. Starts with warning. |
Pattern ^error$
| Sample line | Result |
|---|---|
1: error |
Match. Exactly error. |
2: errors |
No match. Extra s before the end. |
3: error7 |
No match. Extra digit before the end. |
4: error.log |
No match. Extra .log before the end. |
5: erro |
No match. The final r is missing. |
6: warning |
No match. Different letters. |
Pattern [0-9]
| Sample line | Result |
|---|---|
1: error |
No match. No digit. |
2: errors |
No match. No digit. |
3: error7 |
Match. Contains the digit 7. |
4: error.log |
No match. No digit. |
5: erro |
No match. No digit. |
6: warning |
No match. No digit. |
Pattern ^errors*$
| Sample line | Result |
|---|---|
1: error |
Match. Zero copies of s. |
2: errors |
Match. One copy of s. |
3: error7 |
No match. 7 is not a repeated s. |
4: error.log |
No match. Dot suffix is not repeated s. |
5: erro |
No match. The required r is missing. |
6: warning |
No match. Different letters. |
Pattern ^error\.log$
| Sample line | Result |
|---|---|
1: error |
No match. Missing literal .log. |
2: errors |
No match. Missing literal .log. |
3: error7 |
No match. Missing literal .log. |
4: error.log |
Match. Exact letters and literal dot. |
5: erro |
No match. Missing r and literal .log. |
6: warning |
No match. Different letters. |
Pattern error*
| Sample line | Result |
|---|---|
1: error |
Match. One final r. |
2: errors |
Match. Matches the error portion. |
3: error7 |
Match. Matches the error portion. |
4: error.log |
Match. Matches the error portion. |
5: erro |
Match. Zero copies of the final r. |
6: warning |
No match. No erro portion. |
Pattern ^error[0-9]$
| Sample line | Result |
|---|---|
1: error |
No match. Missing a digit. |
2: errors |
No match. s is not a digit. |
3: error7 |
Match. Exactly error plus one digit. |
4: error.log |
No match. Dot suffix is not one digit. |
5: erro |
No match. Missing r and a digit. |
6: warning |
No match. Different letters. |
Mistakes to recognize
Section titled “Mistakes to recognize”Leaving a bracket expression unfinished.
grep '[' samples.txtgrep: Invalid regular expressionThe diagnostic says the regular expression is invalid; it does not identify the bracket. Here [ begins an unfinished bracket expression. Close it, for example [0-9], before judging its matches. An invalid regex is different from a valid pattern that selects nothing.
Expecting quotes to make regex punctuation literal. Single quotes protect a pattern from Bash. grep still interprets its regex operators. Escape the regex dot when you mean a dot.
Using a filename wildcard as a regex. Decide which program receives the pattern and which language that program uses. The real comparison above shows why the distinction changes the result.
Try it yourself
Section titled “Try it yourself”Goal: Select only a complete line consisting of error followed by exactly one digit. Keep its source line number. Do not select error, errors, or error.log.
Hint
Use both boundaries and a single digit class. Repetition is not needed for exactly one digit.
Solution
grep -n '^error[0-9]$' samples.txt3:error7The class supplies one character. Both anchors prevent extra characters around the requested structure.
Reset this lesson
Section titled “Reset this lesson”cd ~/lab/b10ls -AR regexrm -r ~/lab/b10/regexRerun Before you start. If the directory is already absent, skip removal.
^and$anchor the start and end of a line.- Bracket expressions select one character;
*repeats the preceding item zero or more times. - A backslash escapes regex punctuation such as a literal dot.
- Shell filename globs and grep regex use different rules. Quoting preserves the argument for the program that interprets it.
Next, Combining searches chooses a tool and connects the steps to a concrete question.
Further reading
Section titled “Further reading”- On your system:
man grep, sections Regular Expressions and Exit Status;man bash, section Pathname Expansion. - GNU Grep: Regular Expressions.
- GNU Bash: Filename Expansion.
- Ubuntu 24.04: grep(1).