0

我正在使用 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我已经尝试过像or$line[x + 1]甚至是这样的事情,$file[x + 1]但它们并没有产生我想要的结果,因为它们会读入一行,然后读入下一行。谁能告诉我如何检查下一个 $line 是否以 4 开头?

4

1 回答 1

2

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

-and语句的第二部分- - 如果您要查看数组的“边缘”之外,即查看最后一行( $i = $content.Count - 1 ),(($i + 1) -lt $content.Count请确保不会出现 OOB 异常。$content

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

希望这可以帮助。

于 2014-04-21T14:22:02.993 回答