grep or compatible and a given non-empty string not containing newline nor NUL characters:
To count the number of lines containing that string in the output of some
cmd | grep -cFe "$string"
To count the number of non-overlapping occurrences of that string:
cmd | grep -oFe "$string" | wc -l
For the number of possibly overlapping occurrences (for instance, to consider that there are 3 occurrences of
dididid, not just 2):
cmd | grep -Poe "(?=\Q$string\E)." | wc -l
(here also assuming that
$string doesn't contain
If you want to find the
$string as a whole word, for instance so as not to count the
followership, you can add the
-w option to those grep commands above. In effect that will look for occurrences of
follower that are neither preceded nor followed by letters, digits or underscores (so called word characters). To also avoid counting
anti-follower, you'll need to do the exclusion by hand:
cmd | grep -Poe "(?<![\w-])\Q$string\E(?![\w-])" | wc -l
However here, your problems are more about basic shell syntax.
To store the output of a command (minus the trailing newline characters) in a shell variable:
(no space on either side of
=, and avoid the antiquated
To print the contents of a variable followed by one newline character, so as to feed to a command like those
grep ones above:
printf '%s\n' "$variable" | grep ...
echo, remember to quote your parameter expansions when in list contexts)
Though in bash and other shells that have borrowed zsh's
<<< operator, you can also do:
<<< "$variable" grep ...
In any case, if the aim is to check whether a variable contains at least one occurrence of the string, it should just be (with standard shell syntax):
case $variable in
(*"$string"*) echo variable contains the string;;
(*) echo It does not;;
$string may contain newline characters).
Or to check it in the output of
cmd | grep -qFe "$string"
echo cmd output contains the string
echo it does not