Home > Software design >  Count the number of occurrences of a word
Count the number of occurrences of a word

Time:10-12

I have multiple files in a folder.example is below

1stFile:

Start New
 A 
 B 
 C 

Start Old
 A 
 A 
 A 

So I want to count the number of A after we find the word Start. So below is the output I am looking for

'Start New'  '1'
'Start Old'  '3'

I am new to powershell so finding it hard to put the design into code.any help is appreciated.

CodePudding user response:

# Create a sample file.
@'
Start New
 A 
 B 
 C 

Start Old
 A 
 A 
 A 
'@ > test.txt

# Process the sample file.
$i = 0
(Get-Content -Raw test.txt) -split '(?m)^(Start . )\r?\n' -ne '' |
  ForEach-Object {
    if ($i   % 2 -eq 0) { 
      $section = $_ 
    }
    else {
      [pscustomobject] @{
        Section = $section
        Count = (($_ -split '\r?\n').Trim() -eq 'A').Count
      }
    }
  }

The above outputs [pscustomobject] instances with .Section and .Count properties, which render to the display as:

Section   Count
-------   -----
Start New     1
Start Old     3

CodePudding user response:

You could use switch with -File and -Wildcard (or -Regex) parameters and then group the output on the Label property to get the count.

$(
    switch -Wildcard -File .\text.txt {
        '*Start*' {
            $startLabel = $_
            continue
        }
        '*A*' {
            $obj = [pscustomobject]@{
                Label = $startLabel
                Match = $_
            }
            $obj
            continue
        }
    }
) | Group-Object Label -NoElement
Count Name
----- ----
    1 Start New
    3 Start Old
  • Related