CLI tip 2: counting number of matches
Use grep -c
to count the number of input lines containing a given pattern.
# number of input lines containing 'a'
$ printf 'goal\nrate\neat\npit' | grep -c 'a'
3
# number of input lines containing all the vowels
$ grep -icP '^(?=.*a)(?=.*e)(?=.*i)(?=.*o).*u' /usr/share/dict/words
640
# number of input lines NOT containing 'at'
$ printf 'goal\nrate\neat\npit' | grep -vc 'at'
2
With multiple file input, count is displayed for each file separately. Use cat
if you need a combined count.
# separate count for each input file
$ grep -c 'a' names.txt purchases.txt
names.txt:2
purchases.txt:6
# total count for all the input files
$ cat names.txt purchases.txt | grep -c 'a'
8
If total number of matches is required, use the -o
option to display only the matching portions (one per line) and then use wc
to get the count.
# -c gives count of matching lines only
$ printf 'goal\nrate\neat\npit' | grep -c '[aeiou]'
4
# use -o to get each match on a separate line
$ printf 'goal\nrate\neat\npit' | grep -o '[aeiou]' | wc -l
7
Note that if you use ripgrep, you can simply use
-co
or--count-matches
instead of piping to thewc
command.# this behavior is different compared to GNU grep $ printf 'goal\nrate\neat\npit' | rg -co '[aeiou]' 7
Video demo:
See my CLI text processing with GNU grep and ripgrep ebook if you are interested in learning about GNU grep
and ripgrep
commands in more detail.