With GNU grep
or compatible and a given non-empty string not containing newline nor NUL characters:
string=follower
To count the number of lines containing that string in the output of some cmd
:
count=$(
cmd | grep -cFe "$string"
)
To count the number of non-overlapping occurrences of that string:
count=$(
cmd | grep -oFe "$string" | wc -l
)
For the number of possibly overlapping occurrences (for instance, to consider that there are 3 occurrences of did
in dididid
, not just 2):
count=$(
cmd | grep -Poe "(?=\Q$string\E)." | wc -l
)
(here also assuming that $string
doesn't contain \E
)
If you want to find the $string
as a whole word, for instance so as not to count the follower
in followers
or 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:
count=$(
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:
variable=$(cmd)
(no space on either side of =
, and avoid the antiquated variable=`cmd`
syntax).
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 ...
(don't use 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;;
esac
(here $string
may contain newline characters).
Or to check it in the output of cmd
:
if
cmd | grep -qFe "$string"
then
echo cmd output contains the string
else
echo it does not
fi
followers
, if it happened to occur? I'm also noting that your code seems to try to count lines containing the word, not the word itself (if it was to occur several times in one line). Is that an issue? – Kusalananda May 15 '21 at 09:58