Count overlapping occurences of a repeated string using grep/linux/bash -
i'm trying count occurences of repeated string. eg.
echo 'joebobtomtomtomjoebobmike' | grep -o 'tomtom' | wc -l this outputs 1, string 'tomtom' fits twice here. how can make counts both occurences?
thanks!
you can use awk script
{ count = 0 $0 = tolower($0) while (length() > 0) { m = match($0, pattern) if (m == 0) break count++ $0 = substr($0, m + 1) } print count } explanation
we first convert line lower case ignore case. script works shortening string after matching pattern. uses function match() find position pattern matched. if m == 0, means no matches found, can break loop. increment count each iteration of loop, reset $0 string substring starting @ index m + 1.
if save a.awk, can do
echo "joebobtomtomtomjoebobmike" | awk -v "pattern=tomtom" -f a.awk and output 2.
Comments
Post a Comment