03 / WORKING WITH TEXT · LESSON 09

Filtering with grep

Filter complete severity prefixes and distinguish no matches from an error.

13 min · learn at your pace

Match a condition on each line

grep selects lines whose text matches a pattern. ^ anchors a pattern at the start of a line; $ anchors its end. A pattern such as ^WARN selects a severity prefix followed by a space, rather than matching WARNING or a message that happens to mention WARN later.

grep -E uses extended regular expressions, available on both macOS and GNU grep. Do not rely on GNU-only -P. If a search term should be literal text, grep -F avoids giving punctuation regular-expression meaning. Quote the pattern so Bash does not expand it first.

Three useful statuses

Grep returns zero when it selects a line, one when it selects none, and a higher status for an error. An empty report can be a successful result. Using grep ... || true blindly also hides read errors; capture the status and allow only the cases your tool promises to handle.

Use LC_ALL=C for these ASCII severity labels. Filtering is only a first step in an investigation: a matching line is evidence to review, not proof of a cause or a compromise.

Try an example.sh
grep -E '^(WARN|ERROR) ' events.txt
YOUR TURN

Put it into practice.

Write lines beginning exactly `WARN ` or `ERROR ` from `events.txt` to `selected.txt`, preserving order and complete lines. No matches should produce an empty report and exit 0. A missing input must exit nonzero. Print no stdout or stderr for readable inputs.

See an explained solution
One way to solve it.sh
export LC_ALL=C
grep -E '^(WARN|ERROR) ' events.txt > selected.txt
status=$?
if [ "$status" -gt 1 ]; then exit "$status"; fi
exit 0

The expression matches two complete prefixes. The final status treats an empty result as valid without masking file errors.