如何查看TEXT文件的下一行是否以数字开头

时间:2014-04-21 13:19:45

标签: powershell startswith

我正在使用powershell来读取TXT并为它做一些逻辑。 TXT是以非常特定的格式设置的,但是我关心的唯一行以6或4开头。问题是我无法弄清楚如何检查下一行。我从

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

然后我检查每一行

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"
  }
}

我尝试过像$line + 1$line[x + 1]甚至是$file[x + 1]这样的事情,但是他们没有得到我想要的结果,因为他们会读到这行,然后是下一行。任何人都可以告诉我如何检查下一个$行是否以4开头?

1 个答案:

答案 0 :(得分:2)

这将完成您的需求,我改变了文本文件的解析方式,$file = Get-Content $files感觉......错了。使用 for循环,我们创建了一个参考点$i,可用于在数组$content中向前看。

-and声明的第二部分 - (($i + 1) -lt $content.Count - 如果您要超越边缘"确保您不会获得OOB异常。 $content数组,即查看最后一行($ 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"
       }
    }
}

希望这有帮助。

相关问题