Skip to content
shellhacks.dev
Text Processing

Count the matches per file

Count the matching lines in each file with grep -c. With several files grep prefixes each count with the name, and -h removes the prefix for one total.

1 min read
Summarize in AI

You want a count of how many lines match in every file of a directory, not the lines themselves.

Shell
mkdir demo && cd demo
printf 'error\nok\nerror\n' > a.log
printf 'ok\nok\n' > b.log
printf 'error\n' > c.log
grep -c error *.log
echo ---
grep -c error *.log | awk -F: '{ sum += $2 } END { print sum }'
Text
a.log:2
b.log:0
c.log:1
---
3

-c suppresses the normal output and prints how many selected lines each file holds, with the file name in front when there is more than one file. A file with no match is listed with a count of zero, which -l would leave out. The option is described in the grep manual. Sending it through awk adds the counts into a single total.

The number is lines, not matches, so a line with three hits counts once. The count of every occurrence is in count every occurrence with grep -o. When the input is a single stream on standard input, there is no file name and the output is just the number.

Share

More snippets

Text Processing

Search recursively and skip binary files

Skip binary files in a recursive grep with --binary-files=without-match, short form below. Otherwise GNU grep 3.8 prints a notice for every binary hit.

1 min read
Text Processing

Count every occurrence not just lines

Count every occurrence of a word with grep -o piped to wc -l, because grep -c counts the lines that match and a line with three hits counts as one.

1 min read
Text Processing

Match whole words only

Match whole words only with grep -w. A match must sit between non-word characters, and letters, digits and the _ character all count as word characters.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.