Extract lines beginning with CRITICAL: or ALERT: from alerts.log.
Use GNU grep extended regular expressions.
Which command is appropriate?
grep -E enables extended regular expressions, where (A|B) expresses a choice between alternatives.
Detailed explanation
grep -E '^(CRITICAL|ALERT):' alerts.logCorrect. -E makes the grouped alternation work and ^ anchors it at the line start.
Correct. grep -E interprets the group and alternation as two complete prefixes.
grep '^(CRITICAL|ALERT):' alerts.logIncorrect. Basic grep does not treat unescaped parentheses and | as this alternation.
Incorrect. Basic grep does not give unescaped parentheses and the vertical bar the same ERE meaning.
grep -F '^(CRITICAL|ALERT):' alerts.logIncorrect. -F treats the metacharacters as literal text.
Incorrect. Fixed-string mode treats the punctuation literally.
grep '^[CRITICAL|ALERT]:' alerts.logIncorrect. Brackets form a one-character class, not alternatives of whole words.
Incorrect. A bracket expression selects one character, not one of two words.
Try it yourself
An example you can run in a temporary verification environment.
printf 'INFO: ok\nALERT: load\nCRITICAL: disk\n' | grep -E '^(CRITICAL|ALERT):'Expected result
ALERT: load
CRITICAL: diskKey points
- -E selects ERE
- | expresses alternation
- Parentheses group the alternatives
Notes
- Environment: GNU grep 3.x
- Use temporary files and harmless commands for pattern experiments.
- Regular-expression details should be checked against the target GNU implementation.
Foundation review
Place the condition
ERE grouping and alternation express two multi-character prefixes without turning them into a character class.
Check the result
Verify that CRITICAL and ALERT lines match while INFO does not.