Reputation: 97
I'm trying to grep from a given array in a file. I need the count of the array unit and I'm hoping to get the output count per unit, eg: U10 => 2
etc. but when I add more than one unit into the array it seems grep sums up and outputs a single combined count.
Here is my code so far, any help or direction on where to search or where to start would be helpful.
#!/bin/bash
echo "Enter file to check:"
read file
args=("U10" "U12" "U14")
pat=$(echo ${args[@]}|tr " " "|")
grep detected /public/files/$file | grep -Ec "$pat"
Upvotes: 1
Views: 522
Reputation: 123458
You're specifying a regex (U10|U12|U14
) to grep
and seeking for the count. This is why you're observing that you're getting the sum of the count of individual matches.
Specify one pattern at a time:
#!/bin/bash
echo "Enter file to check:"
read file
args=("U10" "U12" "U14")
for pat in ${args[@]}; do
echo -ne "${pat}\t" ; grep detected /public/files/$file | grep -c "$pat"
done
You probably don't need to pass -E
to grep
.
Upvotes: 2