Tiago Veloso
Tiago Veloso

Reputation: 8563

Count number of occurrences of a specific regex on multiple files

I am trying to write up a bash script to count the number of times a specific pattern matches on a list of files.

I've googled for solutions but I've only found solutions for single files.

I know I can use egrep -o PATTERN file, but how do I generalize to a list of files and out the sum at the end?

EDIT: Adding the script I am trying to write:

#! /bin/bash

egrep -o -c "\s*assert.*;" $1 | awk -F: '{sum+=$2} END{print sum}'

Running egrep directly on the command line works fine, but within a bash script it doesn't. Do I have to specially protect the RegEx?

Upvotes: 1

Views: 5300

Answers (3)

bash-o-logist
bash-o-logist

Reputation: 6911

The accepted answer has a problem in that grep will count as 1 even though the PATTERN may appear more than once on a line. Besides, one command does the job

awk 'BEGIN{RS="\0777";FS="PATTERN"} { print NF-1 } ' file

Upvotes: 1

Dimitre Radoulov
Dimitre Radoulov

Reputation: 28000

grep -o <pattern> file1 [file2 .. | *] |
    uniq -c

If you want the total only:

grep -o <pattern> file1 [file2 .. | *] | wc -l

Edit: The sort seems unnecessary.

Upvotes: 3

NPE
NPE

Reputation: 500337

You could use grep -c to count the matches within each file, and then use awk at the end to sum up the counts, e.g.:

grep -c PATTERN * | awk -F: '{sum+=$2} END{print sum}'

Upvotes: 4

Related Questions