Link to home
Start Free TrialLog in
Avatar of bhatia_amrita
bhatia_amrita

asked on

how to count substring in a string

hello
Can anybody tell me how to count number of string in a string.i m a newbie to shell programming so dont know much about it.
Thanks
Amrita
Avatar of sunnycoder
sunnycoder
Flag of India image

Hi bhatia_amrita,

echo $string | awk -F "substring" ' { print NF-1 } '

Sunnycoder
Avatar of da99rmd
da99rmd

Do you want the number of strings in the string like this?
"hi world how you doing" = 5
This you cont like this
echo $string | awk ' { print NF} '

The thing sonnycoder told you about will count the nr of times a certain string is find in a string like this
find "you" in
"Hi you bastard you" = 2
echo $string | awk -F "you" ' { print NF-1 } '
The -F changes the field separator to the word you and the NF is the number of fields.

Here is an awk howto is a good program for handling strings and files separated by anything.
http://www.cs.uu.nl/docs/vakken/st/nawk/nawk_toc.html

and here is a good bash scripting manual
http://www.dei.isep.ipp.pt/so1/ftpdei/sop1/Docs/Linux/abs-guide/

and here a sed manual a stream editor:
http://gnu.intissite.com/software/sed/manual/html_chapter/sed_toc.html

/Rob




Avatar of bhatia_amrita

ASKER

me actually looking for counting number of occurences of a  given substring in a string
ASKER CERTIFIED SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thnx a ton :)