我有一个.txt文件目录,看起来像这样:
[LINETYPE]S[STARTTIME]00:00:00 [LINETYPE]P[STARTTIME]00:00:00 [LINETYPE]B[STARTTIME]00:59:00 [LINETYPE]C[STARTTIME]00:59:00 [LINETYPE]C[STARTTIME]00:59:30 [LINETYPE]S[STARTTIME]01:00:00 [LINETYPE]P[STARTTIME]01:00:00 [LINETYPE]B[STARTTIME]01:59:00 [LINETYPE]C[STARTTIME]01:59:00 [LINETYPE]C[STARTTIME]01:59:30 [LINETYPE]S[STARTTIME]02:00:00
I'd like to remove all occurrences of [LINETYPE]S
except the first, which happens to always be 00:00:00 and on the first line, and then re-save the file to a new location.
That is, [LINETYPE]S[STARTTIME]00:00:00
must always be present, but the other lines that start with [LINETYPE]S
need to be removed.
This is what I came up with, which works except it removes all [LINETYPE]S
lines, including the first. I can't seem to figure out how to do that part after Googling for a while, so I'm hoping someone can point me in the right direction. Thanks for your help!
Get-ChildItem "C:\Users\Me\Desktop\Samples" -Filter *.txt | ForEach-Object {
Get-Content $_.FullName | Where-Object {
$_ -notmatch "\[LINETYPE\]S"
} | Set-Content ('C:\Users\Me\Desktop\Samples\Final\' + $_.BaseName + '.txt')
}
最佳答案
请尝试以下操作:
Get-ChildItem "C:\Users\Me\Desktop\Samples" -Filter *.txt |
Foreach-Object {
$count = 0
Get-Content $_.FullName |
Where-Object { $_ -notmatch '\[LINETYPE\]S' -or $count++ -eq 0 } |
Set-Content ('C:\Users\Me\Desktop\Samples\Final\' + $_.BaseName + '.txt')
}
传递给
Where-Object
的脚本块与调用者的作用域相同,因此可以直接更新$count
变量。包含确实包含
[LINETYPE]S
的第一行,因为那时$count
为0,之后$count
递增($count++
);不包括后续的[LINETYPE]S
,因为$count
已经大于0
。
关于windows - 从文件中删除与模式匹配的所有行,但第一次出现的行除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58192947/