0

我对脚本很陌生(几周),很高兴得到你的帮助。我有一个需要更改的日志文件 (.txt)。

内容总是一样的:

    random text
    random text
    successfull
    error

    random text
    random text
    random text
    error

    ...

我想删除包含单词“error”的行,但前提是上面的行包含单词“successfull”。

到目前为止,我设法从文件中获取了所有匹配的字符串并能够替换它们,但是在此过程中我丢失了其余的文本:

get-content "D:\test.txt" | select-string -pattern "error" -context 1,0 | Where-Object {"$_" -match "successfull" } | %{$_ -replace "error.*"} | Out-File "D:\result.txt"

我真的很感谢你在这里的帮助。

4

1 回答 1

0

您可以使用一些条件逻辑(if语句)来实现目标:

$successful = $false
Get-Content d:\test.txt | Foreach-Object {
    if ($_ -match "successfull") {
        $successful = $true
        $_
    }
    elseif ($_ -match "error" -and $successful) {
       $successful = $false
    }
    else {
        $_
        $successful = $false
    }
}

由于我们将Get-Content结果传递到Foreach-Object,$_成为正在处理的当前行(每一行都被逐一处理)。如果一行包含successfull,那么我们标记$successful$true并仍然输出该行 ( $_)。如果该行包含error,那么我们只会在是 时输出$successful$false。每当我们到达不包含 的行时succcesfull,我们标记$successful$false

实际上没有删除,因为它只是error在满足条件时不显示行。

于 2020-06-19T17:40:33.127 回答