count pattern occurrence per line

awk, regex, sed, unix

Solution

Using awk

awk '{print $1,$2,gsub(/word/,"")}' file
string1 string2 2
string3 string4 3
string5 string6 4

Explanation

- The gsub() function returns the number of substitutions made.

Problem

The desired output keeps for each line the first two 'columns' and adds the number of occurrences of 'word' on that same line. Input: ``` string1 string2 aaaaaaaaa word aaaaaaaa word string3 string4 ccccccccccc word dddaaaaaaacccd word dddddaaaaa word bbbb string5 string6 aaaa word bbbbbbaddd word aaaaa word ccccccdddddddddd word cccccc ``` Desired output: ``` string1 string2 2 string3 string4 3 string5 string6 4 ``` Any suggestions?

Original source