Theo.Fanis
Theo.Fanis

Reputation: 454

Counting grep results

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.

I used a counter that way but it appeared 0.

 let x+=cat $filename | grep "word"

Upvotes: 8

Views: 5701

Answers (2)

Jan Christoph Uhde
Jan Christoph Uhde

Reputation: 711

The oneliner in John's answer is the way to go. Just to satisfy your curiosity:

sum=0
for f in *; do
    x="$(grep 'word' "$f" | wc -l)"
    echo "x: $x"
    (( sum += x ))
done
echo "sum: $sum"

If the line containing the grep and wc does not yield a number you are SOL. That is why you should stick to the other solution or do a pure bash implementation with things like read, 'case and *word*)' or if [[ "$line" =~ "$re_containing_word" ]]; then ...

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 362187

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

Upvotes: 9

Related Questions