1

I am trying to find the amount of times a match occurs from a list of patterns given in the pattern file, to the target file. Here are example target and pattern files:

Target File

are
bare
barely
be
beware
care
clever

Pattern File

be
are

I know that I can do

grep -F -c -f patternFile targetFile

to get the number of strings that have one or more match in the pattern file in them, but I want to count the total number of matches.

Here is where grep is not returning what I really want: In the example above beware is matched by both are and be and should count as two matches, but is only counted as one match by the grep statement above.

1
  • It doesnt have to be with grep if someone knows another quick way to do this from the command line. – Falderol Feb 18 '20 at 23:35
1

Not a one-liner, this small Perl script does the job:

Code:

#!/usr/bin/perl 
use strict;
use warnings;
use feature 'say';

# check for 2 files given as argument
my $f1 = shift @ARGV or die "missing file 1";
my $f2 = shift @ARGV or die "missing file 2";

# load all words to search
open my $fh1, '<', 'file1.txt' or die "$!";
my @wrd = <$fh1>;
chomp @wrd;
# loop on the fiile to be searched
open my $fh2, '<', 'file2.txt' or die "$!";
my $count;
while(my $line = <$fh2>) {
   $count += $line =~ /$_/ for @wrd;
}
say "$count occurrence of ", join' or ',@wrd;

Files:

cat file1.txt 
be
are

cat file2.txt 
are
bare
barely
be
beware
care
clever

Usage:

./test.pl file1.txt file2.txt 
7 occurrence of be or are

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.