How can I count the number of occurrences of a substring in a string using Bash?
EXAMPLE:
I'd like to know how many times this substring :
Bluetooth
Soft blocked: no
Hard blocked: no
...occurs in this string...
0: asus-wlan: Wireless LAN
Soft blocked: no
Hard blocked: no
1: asus-bluetooth: Bluetooth
Soft blocked: no
Hard blocked: no
2: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no
113: hci0: Bluetooth
Soft blocked: no
Hard blocked: no
NOTE I: I have tried several approaches with sed, grep, awk... Nothing seems to work when we have strings with spaces and multiple lines.
NOTE II: I'm a Linux user and I'm trying a solution that does not involve installing applications/tools outside those that are usually found in Linux distributions.
IMPORTANT:
I would like something like the hypothetical example below. In this case we use two Shell variables (Bash).
EXAMPLE:
STRING="0: asus-wlan: Wireless LAN
Soft blocked: no
Hard blocked: no
1: asus-bluetooth: Bluetooth
Soft blocked: no
Hard blocked: no
2: phy0: Wireless LAN
Soft blocked: no
Hard blocked: no
113: hci0: Bluetooth
Soft blocked: no
Hard blocked: no"
SUB_STRING="Bluetooth
Soft blocked: no
Hard blocked: no"
awk -v RS='\0' 'NR==FNR{str=$0; next} {print gsub(str,"")}' "$STRING" "$SUB_STRING"
NOTE: We are using awk just to illustrate!
-P
(Perl) flavor in yourgrep
supported?Bluetooth Soft blocked: no Hard blocked: no
also be counted?grep --version
?