number of occurences of a string

hi,
I have a file where i need to count the occurences of a string ex) 'welcome to unix forum'. can anybody help me out

try this

 awk '{print NF}' file_name

hi srikanth,

This gives me the number of fields in each line of my file but my requirement is different

for ex) let usa ssume my file like this

nasa isro nasa
nasa nasa isro
isro nasa nasa

now i want to count all occurences of 'nasa' in the above file

'grep' is not a proper option coz it always gives the number of lines that the string 'nasa' is present in the file

Do you have grep -o flag ?

grep -o "nasa" input.txt | wc -l

Python alternative:

/usr/bin/python -c 'import re;print len(re.findall("nasa", open("file").read()))'

or

/usr/bin/python -c 'print open("file").read().count("nasa")'

hi vino,

I don't find any grep -o option. can anyone give me UNIX code as python is not available in our development server.

Thanks in advance

try this,

tr ' ' '\n' < txt | grep -cwi "pattern"

awk '
BEGIN {
s=0;}
{
for (i=1;i<=length($0);i++)
{
if(substr($0,i,4) == "nasa")
s=s+1;
}
}
END{
printf("no of occurences=%d\n",s)
}
' file

grep -i "welcome to unix forum" test | wc -w

Note: test is a file name.

This will not give what the OP had requested for :stuck_out_tongue:

>cat txt
good one good
good
good one best
>grep -i good txt | wc -w
7

wc -w in turn would count all the words from the output,
in the above case only the selected pattern is not displayed to count.

Try...

gawk 'BEGIN{RS="[^[:alnum:]]"}/nasa/{s+=1}END{print s}' file

cs u r right

hi jambesh

I think grep -c returns only the number of lines for the welcome to unix forum not the number of occurences.

Regards,
cskumar.