如何统计一个词在每一行中出现的次数

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

我有一个文本文件,我想计算每一行给定单词的出现次数,例如,如果单词是 "text" 并且文件是

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

我期待输出

3
1
0

如何使用 bash 实现此目的?

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

您可以使用 awk.

awk '{print gsub(/text/,"")}' file.txt
while read line
do
echo $(grep -o "text" <<< "$line" | wc -l)
done < file