How to find and print number of fields which contain a substring in awk

So I want to find out how many fields contain the substring “he” in this text document:

The quick brown fox jumped over the lazy dog's back.
The rain in Spain falls mainly on the plain.
The rain in Spain also falls on the mountains.

The output should be 6, but I don’t know what to do. So far I have this for my script file:

{ count = 0
    if ($0 ~ /he/)
     count = count + 1

print count
}

My problem is is that it stops at the first instance of ‘he’. I need it to go throughout the entire file, how do I do this?

Try the following awk code that count all all occurrences of words or strings:

awk 'BEGIN { RS=FS } 
{if ( $0 ~ /he/ ) count++} 
END{ print count}' input_file

HTH


Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki