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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

QUICK - Need to search for total matches of string in file!

Status
Not open for further replies.

eholdo

Technical User
May 30, 2002
31
US
HELP!

I can't figure this out. I just want a total count of a
string in a file. Using the grep -c option just gives me
the line count, but misses is I have multiple matches on a
line.

THANKS!!!
 
The following is a start. It will not find partial word matches like 'textual' only 'text' as a distinct word. This script could also be squashed down into a one-liner or better yet a script that takes an argument.

awk 'BEGIN{
text="text"
}
/text/{
for( i=1 ;i<=NF ;i++ ){
if( $i == text ){
ct++
}
}
}
END {
print ct, &quot;matches&quot;
}' < input Cheers,
ND [smile]

bigoldbulldog@hotmail.com
 

'text this line text, textual foo text &quot;text bar&quot; wow'

How many matches are there? 1, 2, 3, 4, 5?

I see only 2 based on the above implementation ;)

&quot;Depends on what the meaning of the word 'is' is&quot; [(c) you-know-who] ;)

vlad
 
How about:
Code:
perl -n -e '$count++ for /foo/g;' -e 'END{print &quot;$count\n&quot;}' < bar
Cheers, Neil
 
Vlad -

Good point. My implementation gives 3 counts for the line

'text this line text, textual foo text &quot;text bar&quot; wow'

We need a tighter spec. These types of searches can sometimes get out of hand. Cheers,
ND [smile]

bigoldbulldog@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top