1

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"

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks devnull, it works as I wanted it to work! Thanks Again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.