Use Case Implementation Process
Remove empty lines from a file with PowerShell
Categories:
Here's a quick way to remove blank lines from a file using PowerShell. This will also remove lines that only have spaces.
(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt
- gc is an abbreviation for get-content
- The parenthesis causes the get-content command to finish before proceeding through the pipeline. Without the parenthesis, the file would be locked and we couldn't write back to it.
- ? is an abbreviation for "where-object". Essentially, an "if" statement
- -ne is an operator that means "not equal to"
- trim() is a method removes lines that contain spaces but nothing else which is what I needed in my case.
Thanks to Leon @ http://secretgeek.net/gc_blank.asp for inspiration! PowerShell is pretty handy!