Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting grep results

Tags:

bash

sh

I'm new to bash so I'm finding trouble doing something very basic. Through playing with various scripts I found out that the following script prints the lines that contain the "word"

for file in*; do
    cat $file | grep "word"
done

doing the following:

for file in*; do
    cat $file | grep "word" | wc -l
done

had a result of printing in every iteration how many times did the "word" appeared on file.

  • How can I implement a counter for all those appearances and in the end just echo the counter?

I used a counter that way but it appeared 0.

 let x+=cat $filename | grep "word"
like image 459
Theo.Fanis Avatar asked Apr 29 '18 18:04

Theo.Fanis


1 Answers

You can pipe the entire loop to wc -l.

for file in *; do
    cat $file | grep "word"
done | wc -l

This is a useless use of cat. How about:

for file in *; do
    grep "word" "$file"
done | wc -l

Actually, the entire loop is unnecessary if you pass all the file names to grep at once.

grep "word" * | wc -l

Note that if word shows up more than once on the same line these solutions will only count the entire line once. If you want to count same-line occurrences separately you can use -o to print each match on a separate line:

grep -o "word" * | wc -l
like image 194
John Kugelman Avatar answered Sep 18 '22 18:09

John Kugelman