如何在 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