[grep] Print only text that matches a regular expression

Created on November 30, 2026

Use grep -o to print each nonempty match on its own line. Here -E enables extended regular expressions, and [0-9]+ matches one or more digits.

printf 'name=alice id=123 id=456\nstatus=ok\n' | grep -Eo 'id=[0-9]+'
id=123
id=456

Both matches came from the same input line. status=ok contains no match and produces no output.

Print the whole matching line

Without -o, grep prints each line containing a match.

printf 'name=alice id=123 id=456\nstatus=ok\n' | grep -E 'id=[0-9]+'
name=alice id=123 id=456

Parentheses in id=([0-9]+) still make grep -o print the entire match. You can use sed to extract a capture group.

Check the exit status

When nothing matches, grep prints nothing and exits with status 1.

printf 'status=ok\n' | grep -Eo 'id=[0-9]+'
printf '%s\n' "$?"
1

Reference

Shell command grep