windows - 从文件中删除与模式匹配的所有行,但第一次出现的行除外

标签 windows powershell

我有一个.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/

相关文章:

python - 在 PowerShell 中设置 Python 的路径?

azure - Azure 中的存储消耗报告

c++ - 访问位图资源失败,错误代码为 0x716

Windows 批量移动到可能不存在的目录

java - 设置 Emacs 23.4、CEDET 1.1 和 SemanticDB 以在 Windows 上使用 GNU Global

powershell - 从 WebJob/WebApp 访问注册表

c++ - WM_TIMER 动画闪烁

c++ - Windows API : could WM_DESTROY be sent without WM_CLOSE beforehand?

windows - 定期自动下载 Cacti 天气图

Powershell:以递归方式替换目录中选择子文件中的字符串