使用正则表达式和PowerShell

时间:2017-06-22 11:54:40

标签: regex powershell

我必须从文本文件中提取一些数据,但在此之前我需要使用此规则连接几行:如果行以空格开头,那么它应该与前一行合并,而不是以一个空白。对所有以空格开头的连续行执行此操作。

虽然我已为which can be found here along with the sample创建了正则表达式,并且替换面板显示了所需的输出,但我无法将其合并到PowerShell脚本中:

Get-ChildItem .\abc.txt | ForEach-Object {
    $content = Get-Content $_.FullName
    #remove all lines starting with *
    $content | Select-String -Pattern "\*" -NotMatch |
        %{ $_ -replace '(\s+^\n?\s)', "" } |
        Set-Content $_.FullName 
}

当正则表达式工作时,我无法理解我应该如何使它工作。

1 个答案:

答案 0 :(得分:3)

要将行与-replace运算符合并,您需要在单个字符串中包含文件内容。在PowerShell v3及更新版本上,您可以使用参数Get-Content调用-Raw来实现这一目标:

(Get-Content $_.FullName -Raw) -replace '\r?\n\s+' | Set-Content $_.FullName

在较旧的PowerShell版本上,Get-Content到[{1}}的输出:

Out-String