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 |.
The command prints eight lines — every error in the log and nothing else.
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 textERROR|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 -Esplits 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.