events.txt has one line with error twice and one line with error once.
Print the number of lines containing error, not the total number of occurrences.
Which command is correct?
grep -c counts lines containing at least one match. Multiple matches on the same line still count as one line.
Detailed explanation
grep -o 'error' events.txt | wc -lIncorrect. -o emits each occurrence, so the pipeline counts three matches rather than two lines.
Incorrect. -o emits each occurrence, so the pipeline counts three matches rather than two lines.
grep -c 'error' events.txtCorrect. grep -c returns the number of matching lines.
Correct. grep -c returns the number of matching lines.
wc -l events.txtIncorrect. wc -l counts every line in the file, including non-matching lines.
Incorrect. wc -l counts every line in the file, including non-matching lines.
grep -n 'error' events.txtIncorrect. -n prints matching lines with numbers rather than only their count.
Incorrect. -n prints matching lines with numbers rather than only their count.
Try it yourself
An example you can run in a temporary verification environment.
printf '%s\n' 'error error' ok error | grep -c 'error'Expected result
2Key points
- -c counts matching lines
- Multiple matches on one line count once
- -o piped to wc counts occurrences
Notes
- Environment: GNU grep 3.x
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.