Script to Serach pattern and give number of occurrences

Hi,

I want a script which search for a pattern "good" in a huge file and provide me number of occurences of such pattern in a file.

lets say i have a file test.txt contents as below

good is good
but good is sometime bad and sometime good
you are very good and good is always good

So the script should search for pattern "good" and give me output as "7" as good appears seven time

Now my concern is

I tried in linux with code. It is giving me desired output.
But on SunOS "-o" not working.

grep -o good test.txt|wc -w 

So please advise script by which I can achieve it with sed/awk or any other command.
Many thanks

akshay@Aix:/tmp$ awk '{count+=gsub(/good/,x)}END{print "Total is "count}' file
Total is 7
akshay@Aix:/tmp$ cat file
good is good
but good is sometime bad and sometime good
you are very good and good is always good

Use nawk on Solaris/Sun OS

1 Like

Excellent mate it worked.Thanks
Could you please explain how its works and what is gsub

The gsub() ( global substitution ) function returns the number of substitutions made, it's just summed up and printed in END block.

1 Like

great thanks..one more question
Why gsub didnt work with awk.

Pardon me, I didn't get your question, could you please elaborate your problem.

Hi.

There is a ggrep on some Solaris systems:

$ ggrep -o good data1|wc -w
       7

for:

OS, ker|rel, machine: SunOS, 5.10, i86pc
Distribution        : Solaris 10 10/08 s10x_u6wos_07b X86
ggrep grep (GNU grep) 2.5

See if you have ggrep (and many other GNU utilities):

$ which ggrep 
/usr/sfw/bin/ggrep

Best wishes ... cheers, drl

1 Like

Not available in my server. below is server details

SunOS xxxxxxxx 5.9 Generic_122300-31 sun4u sparc SUNW,Sun-Fire-880