簡體   English   中英

從文件中刪除空行

[英]Removing Empty Lines from a file

如何在此“代碼塊”中使用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
  } 

Get-Content已經將文件按行尾`r`n ,因此`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
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM