[powershell] remove empty lines from text file with PowerShell

I know that I can use:

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

to remove empty lines. But How I can remove them with '-replace' ?

This question is related to powershell text-files lines

The answer is


I found a nice one liner here >> http://www.pixelchef.net/remove-empty-lines-file-powershell. Just tested it out with several blanks lines including newlines only as well as lines with just spaces, just tabs, and combinations.

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

See the original for some notes about the code. Nice :)


Similar questions with powershell tag:

Similar questions with text-files tag:

Similar questions with lines tag: