我需要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;
这确实假定您的文件是一致的,并且====-
始终跟随####
并且两者是平衡的。否则,需要额外的逻辑来说明这一点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句