Remove empty lines from a file using Powershell.

I needed to remove the blank lines from a file.

Normally when I need to do this, I use a regular expression in TextPad. (replace "\r\n\r\n" with "\r\n"... and iterate) -- but TextPad wasn't available on this machine, and I couldn't connect to the internet to grab it.

So I fired up PowerShell and messed around with the syntax until it worked.

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

I don't know if that was the prettiest way to do it -- but I got the result I needed ;-)

The nicest thing was that I didn't need to look anything up -- I just tried variations until I got the result I wanted. I didn't remember the syntax of the 'where' statement or the 'not equal to' operator -- I guessed and got them right within one or two guesses. Nice language design, Bruce!

(I didn't even remember the command 'gc' -- but since i wanted the powershell equivalent of the 'type' command, so i entered 'alias type' and found 'Get-Content' is the powershell equivalent of 'Type' which i guessed was also known as just 'gc')

 

I'm currently writing a book about how to build your first product. If building a product is something you'd like to do, then sign up to be notified when the book is available.

Your comment, please?

Your Name
Your Url (optional)
Note: I may edit, reuse or delete your comment. Don't be mean.