You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Michael Diamond edited this page Apr 23, 2020
·
7 revisions
Consider using grep -c instead of grep | wc
Problematic code:
grep foo | wc -l
Correct code:
grep -c foo
For multiple files
Instead of:
grep foo *.log | wc -l
You can pipe all the file contents into grep (passing the files directly to grep causes -c to print each file's count separately, rather than the total):
cat *.log | grep foo -c
Rationale:
This is purely a stylistic issue. grep can count lines without piping to wc.
Often this number is only used to see whether there are matches (i.e. == 0). In these cases it's clearer and more efficient to use grep -q and check its exit status:
if grep -q pattern file;thenecho"The file contains the pattern"fi
Also note that in foo | grep bar | wc -l, wc will mask the exit code of grep by default (i.e. without set -o pipefail), and always return success. If replacing with foo | grep -c bar, grep will exit non-zero when there are no matches. This is generally desirable (see above), but may require handling when used with set -e.
Exceptions
If you find piping to wc is clearer in a given situation it's fine to ignore this error.