Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do you count occurences of a string in a file? 1

Status
Not open for further replies.

eholdo

Technical User
May 30, 2002
31
US
Tried using grep -c option to find the number of times a string is found in a text file, but this bypasses multiple occurences of the string on the same line.

Is there a way of capturing total matches of a string in a text file?

Thanks!
Erik
 
Erik:

You might try awk (nawk in my case since I'm using Solaris 7). The global substitute command, gsub returns the number of substitiutions made in $0. I just cycle thru x.file counting the number made.

Regards,

Ed


string="test"
nawk -v str="$string" ' BEGIN { cnter=0 }
{
cnter+=gsub(str, "x")
}

END { printf("count is: %d\n", cnter) } ' x.file
 
Great help. One question, the line I am reading is very long, and I'm getting a "too long" error. Any other way of accomplishing this with nawk or awk?

Thanks!!!
Erik
 
Thanks Erik:

I've heard the GNU version of awk, gawk, doesn't have this problem. Maybe someone in this forum can verify that.

The GNU tools are available at among other places.

Regards,


Ed
 
grep "string" file | wc -l -Danny
dan@snoboarder.net






 
the last script can produce wrong out put for example
if in the file you have "*string*" this occurence will be counted too
try other thing.
good luck
-SimoYaz
 
Yes your right, it does depend on the "*string*" -Danny
dan@snoboarder.net






 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top