使用PowerShell从文本文件中删除空行

Sul*_*man 25 powershell lines text-files

我知道我可以使用:

gc c:\FileWithEmptyLines.txt | where {$_ -ne ""} > c:\FileWithNoEmptyLines.txt
Run Code Online (Sandbox Code Playgroud)

删除空行.但我如何用'-replace'删除它们?

Ran*_*tka 48

我在这里发现了一个漂亮的衬垫>> http://www.pixelchef.net/remove-empty-lines-file-powershell.刚刚测试了几个空白行,包括换行符,以及只有空格的行,只有标签和组合.

(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt
Run Code Online (Sandbox Code Playgroud)

有关代码的一些注释,请参阅原始文档.好:)

  • 总的来说,我认为我更喜欢`(gc file.txt)| ?{-not $ _。IsNullOrWhiteSpace()} | set-content file.txt`,因为它可以更清楚地表达意图,但实际上是一样的。 (3认同)
  • IsNullOrWhiteSpace是System.String对象的静态方法,在PowerShell中调用它的正确方法如下:[[String] :: IsNullOrWhiteSpace({your string})`。基于Neil Barnwell注释的正确命令行如下:`(gc file.txt)| ?{-not [String] :: IsNullOrWhiteSpace($ _)} | set-content file.txt` (2认同)

Rai*_*ner 16

Randy Skretka的这段代码对我来说很好,但我遇到了问题,我在文件的末尾仍然有一个换行符.

(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt

所以我最后添加了这个:

$content = [System.IO.File]::ReadAllText("file.txt")
$content = $content.Trim()
[System.IO.File]::WriteAllText("file.txt", $content)
Run Code Online (Sandbox Code Playgroud)


mjo*_*nor 8

如果您还想排除仅包含空格字符的文件,则可以使用-match而不是-eq:

@(gc c:\FileWithEmptyLines.txt) -match '\S'  | out-file c:\FileWithNoEmptyLines
Run Code Online (Sandbox Code Playgroud)


小智 6

不是专门使用-replace,但是使用-notmatch和 regex解析内容时可以获得相同的效果。

(get-content 'c:\FileWithEmptyLines.txt') -notmatch '^\s*$' > c:\FileWithNoEmptyLines.txt
Run Code Online (Sandbox Code Playgroud)


小智 1

你无法进​​行替换,你必须用某些东西来替换某些东西,而你两者都没有。

  • 你说的是苹果和橙子。删除和替换显然是不同的。您所拥有的基本上可以工作,但也许您正在尝试重建现有文件但不包含空白。PS C:\> $text=get-content a.txt PS C:\> $text | 其中 {$_} | 输出文件a.txt (2认同)