Low Orbit Flux Logo 2 F

AWK How To Count Occurrences

Assume that you have a text file that looks like this:

data.txt
1 2 3 4 4 3 2 1 5 6 7 8 8 7 6 5 1 5 6 2 abc xyz edw abc

You can count the number of lines that match the pattern “abc” like this. The total would be one since one line has that string.


awk '/abc/{c++} END {print "Total matched: ", c}' data.txt

You can also count the number of fields or words contain the string “abc”. You do this by changing the record separator to split on spaces. This will treat each word as an entire record instead of each line. This will now count the number of words that match. The total is now two since two words match.


awk -v RS='[ ]' '/abc/ {c++} END{print "Total matched:", c}' data.txt