Search code examples
powershellstartswith

How to see if the next line of a TXT file starts with a number


I am using powershell to read in a TXT and do some logic to it. The TXT is setup in a very specific format but the only lines I care about start with a 6 or 4. The problem is that I am not able to figure out how to check the next line though. I start off with

$files = Get-ChildItem $source *.*
$file = Get-Content $files

and then I check each line

foreach ($line in $file) {
  if ($line.StartsWith("6")) {
    Write-Host "This line starts with 6"
  } elseif ($line.StartsWith("4")) {
    Write-Host "This line starts with 4"
  } elseif (($line.StartsWith("4")) -and (NEXT LINE STARTS WITH 4)) {
    Write-Host "This line starts with 4 and the next line starts with 4"
  } else {
    Write-Host "This line does not start with 6 or 4"
  }
}

I have tried doing things like $line + 1 or $line[x + 1] and even $file[x + 1] but they did not yield the results that I desire because they would read into the line and next the next line. Can anyone tell me how I can check to see if the next $line starts with 4?


Solution

  • This will accomplish what you need, I changed the way text files are being parsed as $file = Get-Content $files feels...wrong. Using a for loop we create a reference point $i which can be used to look ahead in the array $content.

    The second part of -and statement - (($i + 1) -lt $content.Count - makes sure you don't get OOB exception if you were to look beyond the "edge" of the $content array, ie when looking at the last line ( $i = $content.Count - 1 ).

    $files = Get-ChildItem $source *.*
    foreach($file in $files){
        $content = Get-Content $file
        for($i = 0; $i -lt $content.Count; $i++){
           $line = $content[$i]
           if ($line.StartsWith("6")) {
               Write-Host "This line starts with 6"
           } elseif ($line.StartsWith("4")) {
                Write-Host "This line starts with 4"
           } elseif (($line.StartsWith("4")) -and (($i + 1) -lt $content.Count)) {
                $nextLine = $content[$i+1]
                if($nextLine.StartsWith("4")){
                    Write-Host "This line starts with 4 and the next line starts with 4"
                }
           } else {
                Write-Host "This line does not start with 6 or 4"
           }
        }
    }
    

    Hope this helps.