From 0353cf8f3bebee9fe64c3f152545f0e4b5c42aa2 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 5 Apr 2014 16:52:55 -0700 Subject: [PATCH] Created SC2026 (markdown) --- SC2026.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 SC2026.md diff --git a/SC2026.md b/SC2026.md new file mode 100644 index 0000000..41b2a23 --- /dev/null +++ b/SC2026.md @@ -0,0 +1,24 @@ +## Consider using grep -c instead of grep|wc. + +### Problematic code: + + grep foo | wc -l + +### Correct code: + + grep -c foo + +### Rationale: + +This is purely a stylistic issue. `grep` can count lines without piping to `wc`. + +Note that in many cases, this number is only used to see whether there are matches (i.e. `> 0`). In these cases, it's better and more efficient to use `grep -q` and check its exit status: + + if grep -q pattern file + then + echo "The file contains the pattern" + fi + +### Contraindications + +If you e.g. want to count characters instead of lines, and you actually care about the number and not just whether it's greater than 0. \ No newline at end of file