繁体   English   中英

powershell - 在文件中匹配后删除 n 行

[英]powershell - delete n lines after match in file

我的测试文件如下所示:

aa
xxxxx test1 vraarxxxerv
remove1
remove2
remove3
must stay 1
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
test2
remove1 efsd
remove2 esf 
remove3 gr rgsv
must stay 2
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
xx test3
remove1 efsd
remove2 esf 
remove3 gr rgsv
must stay 3
aaaaaa
aaa
aaaaa
aaaaaaaa
aa

想法很简单 - 查找包含字符串 test1、test2 和 test3 的行并删除下 3 行

我的代码是

 $search = 
'test1',
'test2',
'test3'



foreach ($item in $search) {
echo "."
$linenumber= Get-Content .\test.txt | select-string $item
$linenumber.LineNumber

Get-Content .\test.txt | Where-Object {
    -not ($_.ReadCount -ge $linenumber.LineNumber -and $_.ReadCount -le $linenumber.LineNumber+3) 
} | Out-File -FilePath .\test.txt



}

但它只是创建空的 test.txt 文件 - 我做错了什么..? 我想有一个文件,其中 remove1 remove2 和 remove3 行不存在 - 它们总是不同的,所以我不能寻找“删除”文本,它们只是一个例子。 必须保留 1,2,3 行只是为了确保它没有根据我的需要删除更多行...

尝试这个:

$lines = Get-Content .\test.txt 
$rem = @()
@("test1","test2","test3") | Foreach {
  $rem += $lines[(($lines | Select-String -Pattern "$_").LineNumber)..(($lines | Select-String -Pattern "$_").LineNumber+2)]
}
Compare-Object $lines $rem | Select-Object -ExpandProperty InputObject | Set-Content .\test.txt

您可以使用 switch 语句并实现一个小 state 机器来跳过您想要删除的行

    $state=0
    switch -File test.txt -Regex ($_) {
        'test[123]' {
            $state = 1
            Write-Output $_            
            Continue
        }
        default {
            if ($state -eq 0) {Write-Output $_}
            elseif ($state -lt 4) {$state++}
            else {$state = 0; Write-Output $_}
        }
    }

例子

$state=0
@'
aa
xxxxx test1 vraarxxxerv
remove1
remove2
remove3
must stay 1
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
test2
remove1 efsd
remove2 esf 
remove3 gr rgsv
must stay 2
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
xx test3
remove1 efsd
remove2 esf 
remove3 gr rgsv
must stay 3
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
'@ -split "`r`n" | % {    
    switch -Regex ($_) {
        'test[123]' {
            $state = 1
            Write-Output $_            
            Continue
        }
        default {
            if ($state -eq 0) {Write-Output $_}
            elseif ($state -lt 4) {$state++}
            else {$state = 0; Write-Output $_}
        }
    }    
}

返回

aa
xxxxx test1 vraarxxxerv
must stay 1
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
test2
must stay 2
aaaaaa
aaa
aaaaa
aaaaaaaa
aa
xx test3
must stay 3
aaaaaa
aaa
aaaaa
aaaaaaaa
aa

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM