Treating the string as consisting of fields that are delimited by abc
:
$ echo abcsdabcsdabc | awk -F 'abc' '{ print (length > 0 ? NF - 1 : 0) }'
3
The number of occurrences of the delimiter abc
is 1 minus the number of fields that it delimits.
$ echo abcsdabcsdabc | awk '{ n=0; while (sub("abc", "xxx")) n++; print n }'
3
This replaces the substring abc
from the line with xxx
and counts the number of times this is done, then outputs that number. The n=0
is not needed if there is only one line of input.
The gsub()
function in awk
returns the number of substitutions made, so the above could be simplified into
$ echo abcsdabcsdabc | awk '{ print gsub("abc", "xxx") }'
3
In bash
, you can do the same thing as in that awk
program that uses sub()
:
string=abcsdabcsdabc
n=0
while [[ $string == *abc* ]]; do
n=$(( n+1 ))
string=${string/abc/xxx} # replace first occurrence of "abc" with "xxx"
done
printf '%d\n' "$n"
This uses a while
loop to replace the substring abc
from the value in $string
with xxx
until no further occurrences of abc
is found in $string
, just as the second awk
program above does.
bash
? – Kusalananda Mar 20 '19 at 09:12echo abcsdabcsdabc | grep -o abc| wc -l
, to count the lines. – zeppelin Mar 20 '19 at 09:30