Bash - Counting substrings in a string
I'd use grep -o
to extract the desired string from the output:
#!/bin/bashCommandResult="Interface Chipset Driver mon0 Unknown iwlwifi - [phy0]wlan0 Unknown iwlwifi - [phy0]Interface Chipset Driver mon12 Unknown iwlwifi - [phy0]wlan0 Unknown iwlwifi - [phy0]"for InstanceId in $(grep -o 'mon[0-9]\+' <<< "$CommandResult") ; do echo "found $InstanceId "$(grep -c "$InstanceId" <<< "$CommandResult")' times'done
Wanted to share another solution. 3,5 years later, but better late than never I guess. ;)
I was working on a script that had to do the same, that is get the number of substrings in a string, and I was using count=$(echo '$string' | grep -o ... | wc -l)
at first.
I got what I wanted, but when looping through ~1500 files with 0...8000 lines in each the performance was just terrible: the script took about 49 minutes to complete.
So, I went and searched for alternative approaches and eventually found this:
InstanceId="mon0";tmp="${CommandResult//$InstanceId}"count=$(((${#CommandResult} - ${#tmp}) / ${#InstanceId}))
Got the same result but waaaay quicker, in 8-9 minutes.
Explained:
tmp="${CommandResult//$InstanceId}"
This removes all occurrences of $InstanceId
from $CommandResult
and places it in tmp
.
Actually we're using substring replacement here with replacement string missing. Syntax for substring replacement is ${string//substring/replacement}
(this replaces all occurrences of substring with replacement).
count=$(((${#CommandResult} - ${#tmp}) / ${#InstanceId}))
This gives us the number of occurrences of $InstanceId
in $CommandResult
.${#string}
gives string length so (${#CommandResult} - ${#tmp])
is length of all occurrences of $InstanceId
(remember, we removed all occurrences of $InstanceId
from $CommandResult
and placed the result in $tmp
).
Then we just divide the substraction with length of $InstanceId
to get the number of $InstanceId
occurrences.
For further info about substring replacement and string length, see e.g. https://www.tldp.org/LDP/abs/html/string-manipulation.html.