remove empty lines from text file with PowerShell

后端 未结 11 1824
情话喂你
情话喂你 2020-12-08 19:32

I know that I can use:

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

to remove empty lines. But How

11条回答
  •  醉酒成梦
    2020-12-08 20:10

    This piece of code from Randy Skretka is working fine for me, but I had the problem, that I still had a newline at the end of the file.

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

    So I added finally this:

    $content = [System.IO.File]::ReadAllText("file.txt")
    $content = $content.Trim()
    [System.IO.File]::WriteAllText("file.txt", $content)
    

提交回复
热议问题