代码之家  ›  专栏  ›  技术社区  ›  Saeed

PowerShell删除带有下一行的正则表达式字符串

  •  1
  • Saeed  · 技术社区  · 2 年前

    这是一个样本 .txt 文件:

    Line 1
     LineSub 2
      Line2Sub 3
    --
    Line 4
     LineSub 5
      Line2Sub 6
    

    我想运行以下内容,但我的命令不起作用:

    删除线条 --\n 完全,所以后面的下一行应该是 Line 4

    更改 LineSub NewLine (注意前面的空格字符 LineSub

    以下是我尝试工作但失败的命令:

    (Get-Content -Path C:\Users\Saeed\Desktop\file -Raw) -replace " --\n" | Set-Content -Path C:\Users\Saeed\Desktop\file
    (Get-Content -Path C:\Users\Saeed\Desktop\file -Raw) -replace "^--\n" | Set-Content -Path C:\Users\Saeed\Desktop\file
    (Get-Content -Path C:\Users\Saeed\Desktop\file -Raw) -replace "[^--]\n" | Set-Content -Path C:\Users\Saeed\Desktop\file
    (Get-Content -Path C:\Users\Saeed\Desktop\file -Raw) -replace "^[--]\n" | Set-Content -Path C:\Users\Saeed\Desktop\file
    

    唯一有效的是:

    (Get-Content -Path C:\Users\Saeed\Desktop\file -Raw) -replace "--" | Set-Content -Path C:\Users\Saeed\Desktop\file
    

    它删除 -- 但我的文件看起来是这样的:

    Line 1
     LineSub2
      Line2Sub 3
    (THIS IS AN EMPTY LINE WHICH IS NOT REMOVED)
    Line 4
    ...
    

    更新1

    我的预期输出:

    Line 1
     NewLine2
      Line2Sub 3
    Line 4
     NewLine5
      Line2Sub 6
    Line 7
     NewLine8
      Line2Sub 9
    
    1 回复  |  直到 2 年前
        1
  •  3
  •   Santiago Squarzon    2 年前

    以下替换模式应该能够实现您的预期输出:

    (Get-Content path\to\file -Raw) -replace '(?m)^-{1,}\r?\n' |
        Set-Content path\to\file
    

    如果您确定要删除的行始终具有 2个连字符 ,您可以使用 (?m)^-{2}\r?\n 相反看见 https://regex101.com/r/KTQ2ht/1 有关regex的详细信息。

    值得注意的是,上面的模式需要使用 -Raw ,这意味着在替换并写回之前,我们将整个文件内容保存在内存中。如果你想参加 流式传输 为了保存内存,可以使用 switch -Regex -File 旗帜,但是 在这种情况下,我们不能读写同一个文件 :

    & {
        switch -File path\to\file -Regex {
            '^-{1,}$' { continue }  # skip this line
            Default { $_ }          # else, output it
        }
    } | Set-Content path\to\otherFileHere!