Hone

Lessons · Terminal · grep -c counts lines, not matches

grep -c counts lines, not matches

-c reports how many LINES matched. Three matches on one line is still one.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

"How many errors" usually means how many lines, and the two numbers differ exactly when a line mentions the thing twice.

How to think about it

grep -c PATTERN, or grep PATTERN | wc -l. They agree.

Worked example

grep -c ERROR two.log
2. Two lines matched, not four mentions.
grep ERROR two.log | wc -l
The same 2, the long way round.
grep -c zzz two.log
0, and the exit code is 1 -- grep's code says whether it MATCHED, not whether it ran.

Your turn

Count the lines of app.log that mention log.

grep  log app.log

The trap

That exit code ends set -e scripts unexpectedly. A grep that legitimately finds nothing looks like a failure to the shell.

Practise grep -c counts lines, not matches on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.