我需要使用标记1234
查找字符串====-
的代码,然后将####
替换为1234
,然后删除====-1234
行。
文本文件可以具有一组(示例文本A):
A;1;1;####;19/01/2015;08:45:58;UNKNOWN;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
====-1234
或多个组(示例文本B):
A;1;1;####;19/01/2015;08:45:58;UNKNOWN;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
====-1234
A;1;1;####;19/01/2015;08:45:58;UNKNOWN;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
====-5678
到目前为止的代码现在将删除文本文件中的所有内容。有什么帮助吗?
$regex =
@'
(?ms)(.+?####;
.+?)
====-(\d+)
'@
Get-Childitem -Path C:\somedir -Filter *.txt |
foreach {
$text = Get-Content $_
([regex]::matches($text,$regex) |
foreach {
$_.groups[1].value -replace '####',($_.groups[2].value)
}) -join '' |
Set-Content $_.FullName
}
最佳答案
在这种情况下,您可能会受益于使用ArrayList
。下面的方法遍历文件,并在遇到####
或====-
时记下位置。
然后,它可以通过以下方式修改这些位置上的内容:首先直接替换找到####
的索引处的内容,其次使用removeAt
的ArrayList
方法删除遇到====-
的条目:
[System.Collections.Arraylist]$t = Get-Content .\sampleb.txt
$removeAt = @()
$i = 0
while($i -lt $t.count) {
if($t[$i] -match "####") {
$start = $i
}
if($t[$i] -match "====-(\d+)") {
$newval = $t[$start] -replace "####", $matches[1]
$t[$start] = $newval
$removeAt += $i
$start = $i
}
$i += 1
}
foreach($idx in ($removeAt | Sort-Object -Descending)) {
$t.removeAt($idx)
}
$t
产出
A;1;1;1234;19/01/2015;08:45:58;UNKNOWN;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
A;1;1;5678;19/01/2015;08:45:58;UNKNOWN;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
B;0;0;0;319.95;
B;0;0;0;319.89;
这确实假定您的文件是一致的,并且
====-
始终遵循####
,并且两者是平衡的。否则,需要额外的逻辑来说明这一点。
关于regex - Powershell替换和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28048273/