Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count total number of lines of a string before/after a pattern match

I have a file that I need to count the number of lines of a particular string that appears [/done] before a certain pattern match TAG: and then to continue and keep on increasing in counting till the next pattern match and so and so on till the end of file.

My file

    done
    [/done]
    done
    [/done]
    done
    [/done]
    TAG:asdad.bwewk_stght=213.41808
    done
    [/done]
    done
    [/done]
    done
    [/done]
    TAG:asdad.bwewk_stght=3424.43408
    done
    [/done]
    done
    [/done]
    done
    [/done]
    done
    [/done]
    TAG:asdad.bwewk_stght=45424.43308

do note that everything after the TAG: portion can be different every time, different in length and in characters however it will always start with TAG:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So the end result I am after is

    3
    6
    10

what I have got so far, I am able to count all lines that the string occurs on perfectly however unable to wrap my head around how to proceed from here to do what i am after.

     $count = (get-content out.txt | select-string -pattern "[/done]" -SimpleMatch).length | Write-Host

>Solution :

You can read and match lines using regex with a switch:

$index = 0
switch -Regex -File out.txt {
    # if line matches `[/done]`, increase index
    '\[/done\]' { $index++ }
    # if line starts with `TAG:`, output index
    '^TAG:' { $index }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading