Shaharg
Shaharg

Reputation: 1029

How to count the number of appearances of a word in each line

I have a text file and I would like to count for each line the number of appearances of a given word for example if the word is "text" and the file is

abc text fff text text jjj
fff fff text ddd
eee rrr ttt yyy

I expect the output

3
1
0

How can I achieve this with bash?

Upvotes: 0

Views: 182

Answers (3)

Jahid
Jahid

Reputation: 22438

while read line
do
echo $(grep -o "text" <<< "$line" | wc -l)
done < file 

Upvotes: 0

Sean
Sean

Reputation: 333

You can use awk.

awk '{print gsub(/text/,"")}' file.txt

Upvotes: 1

Petr Skocik
Petr Skocik

Reputation: 60143

while read line; do echo "$line" |tr ' ' '\n' |grep text -c ; done < file 

Upvotes: 1

Related Questions