From 39744a0def8526ee56f9c93c672b4477e6634f59 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 1 Jun 2021 21:18:22 -0500 Subject: [PATCH] Add Count The Number Of Matches In A Grep as a unix til --- README.md | 3 +- unix/count-the-number-of-matches-in-a-grep.md | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 unix/count-the-number-of-matches-in-a-grep.md diff --git a/README.md b/README.md index a094959..be8d0e6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1127 TILs and counting..._ +_1128 TILs and counting..._ --- @@ -1047,6 +1047,7 @@ _1127 TILs and counting..._ - [Configure cd To Behave Like pushd In Zsh](unix/configure-cd-to-behave-like-pushd-in-zsh.md) - [Copying File Contents To System Paste Buffer](unix/copying-file-contents-to-system-paste-buffer.md) - [Copying Nested Directories With Ditto](unix/copying-nested-directories-with-ditto.md) +- [Count The Number Of Matches In A Grep](unix/count-the-number-of-matches-in-a-grep.md) - [Create A File Descriptor with Process Substitution](unix/create-a-file-descriptor-with-process-substitution.md) - [Curl With Cookies](unix/curl-with-cookies.md) - [Curling For Headers](unix/curling-for-headers.md) diff --git a/unix/count-the-number-of-matches-in-a-grep.md b/unix/count-the-number-of-matches-in-a-grep.md new file mode 100644 index 0000000..e4f0ed6 --- /dev/null +++ b/unix/count-the-number-of-matches-in-a-grep.md @@ -0,0 +1,29 @@ +# Count The Number Of Matches In A Grep + +My go to way of counting the number of matches in a `grep` of a file is to pipe +it to another command — `wc`. + +Here is what that looks like with the README for [this +repo](https://github.com/jbranchaud/til). This counts the number of lines that +start with `###`. + +```bash +$ grep '^###' README.md | wc -l + 48 +``` + +When `wc` is used with the `-l` flag, it gives a count of the number of lines. +In this case the number of `grep` matches that get piped to it. + +There is another way to do this solely with the `grep` command — using the `-c` +flag. + +```bash +$ grep -c '^###' README.md +48 +``` + +When you include the `-c` (or `--count`) flag with `grep`, instead of the +matches being output, the count of the matches is output. + +See `man grep` for more details.