从文件中删除空行

时间:2018-01-31 19:16:22

标签: regex string powershell

如何在PowerShell中删除PowerShell中的空行和非空行的初始空格

$DIR = "C:\Users\cas\Documents..."
foreach ($file in Get-ChildItem $DIR) {
    (Get-Content -Path $file) |
        ForEach-Object {$_ -replace """, """" } |
        ForEach-Object {$_ -replace "<[^>]*>", "" } |       # removes xml-code
        ForEach-Object {$_ -replace '\s+\r\n+', "`r`n" } | # <= this line doen't work
        Set-Content -Path $file
}

我发现的解决方案确实使用了不同的上下文,如何使用正则表达式完成?

我自己找到了解决方案,现在是:

      foreach($file in Get-ChildItem $DIR){ 
      (Get-Content -Path $file) | 
      ForEach-Object {$_ -replace "&quot;", """" } |  
      ForEach-Object {$_ -replace "<[^>]*>", "" } |   # removes xml-code
      ? {$_.trim() -ne "" } |                         # removes empty lines
      Set-Content -Path $file
  } 

1 个答案:

答案 0 :(得分:0)

Get-Content已经按行结尾拆分文件,因此`r`n将无法匹配任何内容。

只需使用Where-Object

过滤掉这些行
foreach($file in Get-ChildItem $DIR){ 
    (Get-Content -Path $file) |
    ForEach-Object {$_ -replace "&quot;", """" } |
    ForEach-Object {$_ -replace "<[^>]*>", "" } |
    Where-Object {-not [string]::IsNullOrWhiteSpace($_)} |
    Set-Content -Path $file
} 
相关问题