grep -o: Print Only the Matched Text
grep -o prints just the part of each line that matched, each match on its own line.
For pulling a token, version, or ID out of log output, -o extracts the match itself instead of the surrounding line. It is the lightweight alternative to sed or awk for simple extraction.
What it does
grep -o (--only-matching) prints only the matched portion of each line, and prints each match on a separate line, so a line with multiple matches yields multiple output lines. It is commonly paired with -E or -P to capture a structured token.
Common usage
# extract a version number from output
some-tool --version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+'
# pull all IPv4 addresses from a log
grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' access.log
# count total occurrences (not lines)
grep -o ERROR build.log | wc -lOptions
| Flag | What it does |
|---|---|
| -o / --only-matching | Print only the matched text |
| -E | Extended regex (for + ? { } | ( )) |
| -P | PCRE, enabling lookaround for cleaner extraction |
| -m N | Limit the number of matches |
In CI
grep -o is the simplest extractor when you just need a value out of tool output. For capturing a part of a match (not the whole match), use -P with a lookbehind/lookahead, since grep -o has no capture-group output; only the full match is printed.
Common errors in CI
A common mistake is expecting -o to print a capture group; it prints the entire match, so design the regex so the match is exactly the text you want, or use -P lookaround. If -o prints nothing but you expected a value, the regex did not match; test it interactively. On BSD/macOS grep, -o is supported but -P is not, so PCRE-based extraction needs GNU grep.