[英]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 """, """" } |
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 """, """" } |
ForEach-Object {$_ -replace "<[^>]*>", "" } |
Where-Object {-not [string]::IsNullOrWhiteSpace($_)} |
Set-Content -Path $file
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.