简体   繁体   中英

powershell - delete n lines after match in file

my test file looks like this:

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

idea is simple - look for lines contains string test1, test2 and test3 and remove 3 next lines

my code is

 $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



}

but it just create empty test.txt file - what am I doing wrong..? I would like to have file where remove1 remove2 and remove3 lines are not existing - they are always different so I cannot look for "remove" text, they are just an examples. must stay 1,2,3 lines are just to be sure that it haven't deleted more lines as I need...

Try this:

$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

You could use a switch statement and implement a little state machine to skip the lines you'd like to remove

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

Example

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

returns

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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