Linux Labs

Bash: text processing and scripts / Stage 1 of 9

Regular expressions in grep

Not running Starting usually ~20 s
Leave the lesson

Step 3 of 6 · on a machine · 5 min

Several alternatives in one pattern

The errors in the log are written in three ways, and no single word describes them. A pattern can list the alternatives.

Square brackets are a set: they match any one of the characters listed. [Ee] is E or e, [0-9] is any digit, [1-9] is a digit from 1 to 9. The pattern err=[1-9] matches err=5 and err=12 and skips err=0.

The -E option turns on extended syntax. In it, | separates alternatives: a line fits if at least one of them matches. The pattern goes in single quotes so that the shell passes | and the brackets to grep as they are and does not build a pipeline out of |.

bash
grep -E 'ERROR|Error:|err=[1-9]' app.log

The command prints eight lines — every error in the log and nothing else.

Check yourself 1 question

A colleague typed the search without the -E option: grep 'ERROR|Error:' app.log. What will grep print?

  • Without -E, grep does not split the pattern into alternatives: ERROR|Error: is one twelve-character string to it, and it appears nowhere.

  • The pattern is valid without -E: grep accepted it and found no lines. There is no message, and echo $? after the search prints 1.

  • Without -E, | is an ordinary character to grep: it looks for the text ERROR|Error: as a whole, and the log has none.

Without -E, | is an ordinary character to grep, so it searches for the text ERROR|Error: as a whole. The log has no such text, so the output is empty. In basic syntax, GNU grep separates alternatives with \|, but with -E the pattern is easier to read.

Key points

  • Square brackets match one character from a set: [1-9] is a digit from 1 to 9.
  • grep -E splits a pattern into alternatives with |, and a line fits by any of them.
  • A pattern goes in single quotes, or the shell will take | and the brackets for itself.
Ubuntu 24.04
Loading…