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

时间:2012-02-10 06:05:22

标签: powershell text-files lines

我知道我可以使用:

gc c:\FileWithEmptyLines.txt | where {$_ -ne ""} > c:\FileWithNoEmptyLines.txt

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

11 个答案:

答案 0 :(得分:43)

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

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

有关代码的一些注意事项,请参阅原件。尼斯:)

答案 1 :(得分:12)

这段来自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)

答案 2 :(得分:8)

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

@(gc c:\FileWithEmptyLines.txt) -match '\S'  | out-file c:\FileWithNoEmptyLines

答案 3 :(得分:3)

没有专门使用-replace,但您使用-notmatch和正则表达式解析内容的效果相同。

(get-content 'c:\FileWithEmptyLines.txt') -notmatch '^\s*$' > c:\FileWithNoEmptyLines.txt

答案 4 :(得分:1)

你不能替换,你必须用SOMETHING取代SOMETHING,你们两个都没有。

答案 5 :(得分:1)

(Get-Content c:\FileWithEmptyLines.txt) | 
    Foreach { $_ -Replace  "Old content", " New content" } | 
    Set-Content c:\FileWithEmptyLines.txt;

答案 6 :(得分:1)

如果您确实要从文件中过滤空白行,那么您可以尝试这样做:

(gc $ source_file).Trim()| ? {$ _。长度-gt 0}

答案 7 :(得分:1)

要通过RegEx解决此问题,您需要使用多行标记(?m):

((Get-Content file.txt -Raw) -replace "(?m)^\s*`r`n",'').trim() | Set-Content file.txt

答案 8 :(得分:0)

这将删除仅包含空白字符(制表符/空格)的空行或空行。

[IO.File]::ReadAllText("FileWithEmptyLines.txt") -replace '\s+\r\n+', "`r`n" | Out-File "c:\FileWithNoEmptyLines.txt"

答案 9 :(得分:0)

这将从file.txt

中删除尾随空格和空白行
PS C:\Users\> (gc file.txt) | Foreach {$_.TrimEnd()} | where {$_ -ne ""} | Set-Content file.txt

答案 10 :(得分:0)

  

文件

     

PS / home / edward / Desktop> Get-Content ./copy.txt

     

[桌面输入]

     

名称=口径   Exec =〜/ Apps / calibre / calibre

     

Icon =〜/ Apps / calibre / resources / content-server / calibre.png

     

Type = Application *


首先从文件中获取内容,如果在文本文档的每一行中都发现空白,则将其修剪。这将成为传递给where-object的对象,以遍历该数组,查看字符串长度大于0的数组的每个成员。传递该对象以替换您开始使用的文件的内容。制作一个新文件可能会更好... 最后要做的是读回新创建的文件的内容,并查看您的功能。

  

(Get-Content ./copy.txt).Trim() | Where-Object{$_.length -gt 0} | Set-Content ./copy.txt

     

Get-Content ./copy.txt

相关问题