Skip to content
Latchkey

grep -c: Count Matching Lines for CI Gates

grep -c prints the number of matching lines rather than the lines themselves.

Counting is how you turn a log into a metric: how many errors, how many warnings. -c gives a number you can compare against a threshold in CI.

What it does

grep -c (--count) prints a count of matching lines per file instead of the lines. Note it counts lines, not total matches; a line with three matches counts once. To count every match, combine -o with wc -l. With multiple files, -c prints one count per filename.

Common usage

Terminal
# number of error lines
grep -c ERROR build.log

# fail if more than 0 warnings
[ "$(grep -c WARN build.log)" -eq 0 ] || exit 1

# count total matches, not lines
grep -o ERROR build.log | wc -l

Options

FlagWhat it does
-c / --countPrint the count of matching lines
-oPrint each match separately (count with wc -l)
-vCount non-matching lines
-iCase-insensitive counting
-HShow the filename with each count

In CI

When you gate on a count, capture it in a variable and compare with [ ] or (( )); the count goes to stdout while the exit code still follows the match rule (0 if any matched, 1 if none, even when -c printed "0"). So grep -c X file exits 1 and prints 0 when there are no matches.

Common errors in CI

A count check can misbehave under set -e: grep -c X file prints 0 but exits 1 on no match, aborting the step before your comparison runs. Capture it as count=$(grep -c X file || true). Also remember -c counts lines, so a per-occurrence threshold needs grep -o ... | wc -l instead.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →