如何在 PowerShell 中刪除空字串/行?
在很多情況下,你需要刪除 PowerShell 字串陣列或檔案中的空行或字串。本文中,我們不會刪除空字串,而是獲取結果或從非空行中篩選輸出。這樣,我們就可以獲得不含空行的輸出。
考慮以下示例,我們有一個名為 EmptryString.txt 的檔案,需要從中刪除內容中的空行。
文字檔案的內容如下。
PS C:\Windows\System32> Get-Content D:\Temp\EmptyString.txt This is example of empty string PowerShell PowerShell DSC String Array Hello
你只需要應用沒有空行的條件。參見以下程式碼。
示例
Get-Content D:\Temp\EmptyString.txt | where{$_ -ne ""}輸出
This is example of empty string PowerShell PowerShell DSC String Array Hello
同樣,你可以使用以上命令來從字串陣列中刪除空行。例如:
$str = "Dog","","Cat","","Camel","","Tiger" $str PS C:\Windows\System32> $str Cat Camel TigerDog
現在應用相同的邏輯來刪除空行。
示例
$str | where{$_ -ne ""}輸出
PS C:\Windows\System32> $str | where{$_ ne ""}
Dog
Cat
Camel
Tiger
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP