Regular Expressions and Wild Cards
Reading and Building Regular Expressions
A regular expression is a pattern that describes a set of character sequences. You use regular expressions to find text with a recognizable structure, such as alert labels, identifiers, or numeric fields. In Unix commands, understanding both the pattern and the program applying it helps you predict exactly which lines will be selected.
Search a line with the right pattern language
Use grep -E to select extended regular expression syntax. Different tools support different pattern languages, so a pattern that works with one tool may need changes in another. Unless stated otherwise, the examples use case-sensitive matching and the C locale, which you can select by placing LC_ALL=C before a command.
By default, grep searches within each input line:
For example, grep -E 'cat' notes.txt selects both cat and catalog. The pattern need not describe the entire line. Add -x when the entire line must match: grep -Ex 'cat' notes.txt selects cat but rejects catalog.
The shell handles the command before grep receives it. Single quotes protect pattern characters from shell interpretation; the shell removes those outer quotes and passes their contents to grep.
Build a pattern from small pieces
Ordinary characters match themselves. Adjacent pieces must match consecutively and in order: ab matches an a followed immediately by a b. A dot matches any single character within a text line. Brackets specify alternatives for one character; [0-9] matches one digit, while [abc] matches one of the three listed letters.
A quantifier specifies how many times the immediately preceding character, bracket expression, or parenthesized group may occur.
Pattern piece | What it matches |
|---|---|
. | Any one character within a line |
[0-9] | One digit |
x* | Zero or more consecutive occurrences of x |
x+ | One or more consecutive occurrences of x |
x? | Zero or one occurrence of x |
x{2,4} | Between two and four consecutive occurrences of x |
Example: The pattern ab* matches a, ab, and abbb. Only the b repeats, and zero copies are permitted. By contrast, (ab)* repeats the whole parenthesized sequence and can match an empty sequence.
A shell glob such as *.log belongs to a different pattern language. Its star represents an arbitrary filename sequence. In a regular expression, .* represents an arbitrary character sequence because the star repeats the preceding dot.
Control boundaries, alternatives, and literal characters
The anchors ^ and $ require the beginning and end of a line, respectively. They describe positions rather than consuming characters. For whole-line selection, grep -Ex is often easier to read than writing both anchors explicitly.
The vertical bar means alternation: cat|dog matches either sequence. Parentheses control its scope. Thus (INFO|WARN): [0-9]+ describes either label, followed by a colon, one space, and one or more digits. With -x, this describes the whole record; without -x, it may match only part of a longer line.
To match punctuation that otherwise acts as an operator, make it literal. Both \. and [.] match an actual dot. For example, grep -Ex 'data[.]csv' names.txt accepts data.csv but rejects dataXcsv.
Finally, grep -c reports the number of selected lines. A line containing several matches still contributes only one to that count.
What to remember
- Specify the pattern language; grep -E uses extended regular expressions.
- Separate shell quoting from regular expression interpretation.
- Check the item immediately before each quantifier.
- Use -x for whole-line matching and escape literal punctuation.
- Count selected lines separately from individual matches.
Example: Selecting Complete Alert Records
A service writes one alert record per line in service.log. Matching is case-sensitive, and the file contains exactly these seven lines, with no leading or trailing spaces:
Record | Line |
|---|---|
1 | WARN: 418 |
2 | ERROR: 503 |
3 | INFO: 200 |
4 | WARN: 42 |
5 | ERROR: 503 retry |
6 | XWARN: 418 |
7 | WARN: 407 |
Initially, an accepted record must contain either WARN or ERROR, then a colon, exactly one space, and exactly three digits. Nothing else may appear on the line. Assume the C locale.
a) Construct a grep -E command that prints precisely the accepted records.
- Use a group, a parenthesized pattern treated as one unit, to keep the label alternatives together. There are ________ permitted labels, represented by (WARN|ERROR).
- Follow the label with the literal colon and one space. The numeric field requires ________ digits, so its pattern is [0-9]{3}.
- Add -x because the whole line must satisfy the record format. Single quotes protect the pattern during shell processing.
The command is grep -Ex '(WARN|ERROR): [0-9]{3}' service.log.
b) Identify the selected records and determine how many lines the command prints.
- Records 1, 2, and 7 have a permitted label, the required separator, and exactly three digits. Each complete line matches.
- Record 3 has an unsupported label. Record 4 has ________, so its numeric field is too short. Record 5 has extra text after the digits, and record 6 has an extra character before the label. The whole-line requirement rejects both extra-text cases.
- Count one contribution per selected line:
The command prints records 1, 2, and 7, for a total of 3 lines.
c) Revise the command to accept either two or three digits. Determine the new selected-line count.
- Change only the numeric repetition constraint. Its minimum becomes ________ digits and its maximum remains ________ digits, giving [0-9]{2,3}.
- Record 4 now qualifies. The unsupported label and extra characters in records 3, 5, and 6 still violate the unchanged requirements.
- Add the newly accepted record to the previous total:
The revised command is grep -Ex '(WARN|ERROR): [0-9]{2,3}' service.log. It prints records 1, 2, 4, and 7, for a total of 4 lines.
A script uses Bash filename patterns and grep -E regular expressions. Match each pattern element to its meaning in the stated context. For filenames, consider names without a leading period or a directory separator. For regular expressions, consider characters within one input line.
Matches exactly one filename character.
Matches zero or more repetitions of the preceding character or group.
Matches any single input character.
Matches zero or more filename characters without repeating a preceding element.
Bash filename wildcard ?
Bash filename wildcard *
Regular-expression operator *
Regular-expression operator .
A laboratory checks identifier lines with LC_ALL=C grep -Ex '[A-Z]{2}[0-9]{2}' identifiers.txt. Each identifier below is a complete line with no surrounding spaces. Enter exactly 1 if the command selects the line and 0 otherwise.
| Identifier | Selected (1 or 0) |
| AB12 | |
| A123 | |
| XYZ45 | |
| CD07 | |
| ab12 | |
| EF7 | |
| GH89x | |
| JK00 |