remove empty lines from text file with PowerShell

Suliman picture Suliman · Feb 10, 2012 · Viewed 138.3k times · Source

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' ?

Answer

Randy Skretka picture Randy Skretka · Jun 12, 2012

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 :)