SC2126: Use grep -c Instead of grep | wc -l
Replace grep | wc -l with the more efficient grep -c. Learn about related pipeline simplifications for shell scripts.
Detailed Explanation
grep -c vs grep | wc -l
A common shell scripting habit is piping grep output to wc -l to count
matching lines. This is unnecessary because grep has a built-in -c
(count) flag.
The Anti-Pattern
# Unnecessary pipeline
error_count=$(grep "ERROR" logfile.txt | wc -l)
The Fix
# Built-in count
error_count=$(grep -c "ERROR" logfile.txt)
Why -c Is Better
- One process instead of two: Eliminates the pipe and wc process
- Faster: grep stops tracking match content when only counting
- Simpler: Easier to read and understand
Important Difference
grep -c counts lines, not matches. If a line matches multiple times,
it is still counted once:
echo "error error error" | grep -c "error" # Output: 1
echo "error error error" | grep -o "error" | wc -l # Output: 3
If you need to count individual matches (not lines), grep -o | wc -l
is the correct approach.
Related Pipeline Simplifications
| Inefficient | Efficient |
|---|---|
| `grep pattern file | wc -l` |
| `cat file | grep pattern` |
| `grep pattern file | head -1` |
| `grep -v pattern | grep -c ""` |
| `sort file | uniq` |
| `cat file | sort` |
Checking If Any Match Exists
# BAD: Count and compare
if [ $(grep -c "ERROR" log.txt) -gt 0 ]; then
# GOOD: Use grep -q (quiet mode, exits on first match)
if grep -q "ERROR" log.txt; then
echo "Errors found"
fi
grep -q is the most efficient way to check for the existence of a
pattern — it stops reading after the first match.
Use Case
Log analysis scripts, monitoring tools, and any automation that counts occurrences in files. Also useful for code reviews to improve script efficiency and readability.
Try It — Shell Script Linter
Related Topics
SC2002: Useless Cat — Unnecessary Use of cat in Pipelines
Anti-Patterns
SC2012: Don't Parse ls Output in Shell Scripts
Anti-Patterns
Proper Iteration in Shell: Avoiding Word Splitting in For Loops
Quoting
SC2006: Replace Backtick Command Substitution with $()
Deprecated Syntax
Bash Strict Mode: set -euo pipefail Explained
Script Setup