2

How do I get the number of lines before the blank line. For example:

This is a paragraph
This is a paragraph
This is a paragraph

This is a paragraph
This is a paragraph
This is a paragraph
This is a paragraph

The first set should count 3 lines and the second set counts 4 lines. I have used Get-Content .\testing.txt | Measure-Object -line which returns the total number of line but that's not what I wanted.

2 Answers 2

3

Get-Content returns an array so any carriage return or linefeed are lost. Assuming there are no spaces the following returns 3. Adjust accordingly to trim "spaces" if they are not considered characters. $a = Get-Content .\testing.txt ; [array]::IndexOf($a,'')

Edit: The following loops the Content and outputs the number of lines preceding any blank line. An empty line or a line with any number of spaces is considered blank. To treat spaces as not a blank line, remove ".trimend".

$a = Get-Content C:\powershell\tmp.txt ; $i = 0;
while( [array]::IndexOf($a.trimend(' '),'', $i) -gt 0)
{
    $j = [array]::IndexOf($a.trimend(' '),'', $i); $j - $i; $i = $j + 1 ;   
}  
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @Ottak. This can get the total count of the first set. But how to get the total line count of the second set?
@JasonTang See additional edit I added to original answer. It will work for any length file. Tested on a file with 20 sets including sequential empty line sets.
Thank you! I used different approach since the scenario has changed, but your solution answered my initial question. :)
1

This would be stepping through the lines of the file to find first blank.

$lines = Get-Content C:\Dev\PS\3.txt
for ($i = 0; $i -le $lines.Length; $i++) {
    if ($lines[$i].Length -eq 0) {
        break
    }
}
echo $i

2 Comments

Thanks @JasonW. Any ideas how to get the total count of both sets?
How do you mean both sets? In the same file so you want to output 3 and then 4 in different lines for the same file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.