Quantcast
Channel: PowerShell General
Viewing all articles
Browse latest Browse all 10624

Counting the number of occurances of a string on a single line

$
0
0

Hello All,

Can someone kindly help me with the following question please. At first I thougt this was going to be easy, however it is turning out to be a little more difficult than I thought

I have a file called C:\MyFile.txt

The files contains a number of lines as follows

test
test test
tree test blue

Now as you can see there are 4 occurances of the text "test"

now if I do this

 

$counter = 0
${C:\test1.txt} | % {$_ -match "test" | out-null} {$matches.Values | % { $Counter++}}
$counter

$counter is only = to 3

Now I know why this is, basically the RegEx -match is satisfied with the first "test" on the line and therefore goes onto the next iteration of $foreach (or at least I think that is what is happening)

I have also tried select-string to get the result I need i.e. 4 not luck

Can someone please tell me how to solve this issue?

Thanks all
Ernie

 


Viewing all articles
Browse latest Browse all 10624

Trending Articles