![](/img/trans.png)
[英]Using Powershell to output characters (not lines) after a match in a large file
[英]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.