awk to count pattern matches

i have an awk statement which i am using to count the number of occurences of the number ,5, in the file:

awk '/,5,/ {count++}' TRY.txt | awk 'END { printf(" Total parts: %d",count)}'

i know there is a total of 10 matches..what is wrong here?
thanks

Heh. You have to do it in the SAME awk instance.
So you were close...

awk '/,5,/ { count++ } END { print count }' TRY.txt 

that worked! thanks a ton..

that doesn't work for multiple (and sequential) occurrences of a pattern on the same line/record:

echo '1,1,2,5,5,5,6,5,4,5,7'| nawk '{while (sub(/,5,/,",")) t++}END{print t}'

The digit 5 or the string ,5,?

Assumed a string ',5,' - OP will have to confirm.

its a string..

That's only good for one line, and there's no need for a loop:

 awk '{ total += gsub(/,5,/,"") } END { print total }'

Hi.

Another method:

#!/bin/bash -

# @(#) s1       Demonstrate count of strings with awk, field separator.

echo
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version "=o" $(_eat $0 $1) awk
set -o nounset

FILE=${1-data1}

echo
echo " Data file $FILE:"
cat $FILE

echo
echo " Results:"
awk -F",5," '
BEGIN   { t = 0 }
        { t += NF }
END     {print t}
' $FILE

Producing:

% ./s1

(Versions displayed with local utility "version")
Linux 2.6.11-x1
GNU bash 2.05b.0
GNU Awk 3.1.4

 Data file data1:
1,1,2,5,5,5,6,5,4,5,7

 Results:
5

cheers, drl

For one line? Why?

Sorry, I don't know what I was thinking. (But gsub() does avoid the while loop.)

I thought the same, but:

$ echo '1,1,2,5,5,5,6,5,4,5,7' | awk '{ total += gsub(/,5,/,"") } END { print total }'
4

Hi.

In many RE implementations, one cannot have over-lapping matched sections of strings, so the result noted makes sense in that context.

I was surprised that my solution on post # 9 worked, since I would have expected the same behavior with a field split based on a regular expression as separator.

Perhaps the explanation is that for the gsub, part of the string is now replaced by the empty string which makes the next ",5," in the original no longer present, but rather "5,", causing the next one to be considered. For the field split, there is no replacement ... cheers, drl

thats very useful guys. thanks guys.

i was using a separate while loop anyway to read in line by line from a file and then use pattern matching to extract and count ,5,

i was getting confused with awk.. when do you use something like {count++;}? i mean count++ with a semicolon and when do u use it without a semicolon?

if you have a single statement on a line, the ';' is not mandatory.
multiple statements are to be separated with the ';' on the same line.

The semicolon is used to separate commands on a line, here the semicolon is unnecessary.

Regards

thanks vgersh and franklin. that helps a lot.