2 Methods to Remove Empty Lines From File on Windows

2 Methods to Remove Empty Lines From File on Windows

When working on Windows operating system and manipulating files, may needed to remove empty lines from a file to make it easier to read or to be processed further. This tutorial provides 2 methods how to do that.

For testing purpose, create a new file:

(echo Line1& echo.& echo Line2& echo.& echo Line3) > test.txt

Method 1 - CMD

The findstr command allows to find specific text in files. The /v parameter prints only lines that do not contain a match. The following command allows to remove empty lines from a file:

findstr /v "^$" test.txt > temp.txt & move /y temp.txt test.txt >nul

Result is written to temporary file and then renamed.

Method 2 - PowerShell

Run the following command to remove empty lines from a file:

(Get-Content test.txt) | ? {$_ -ne ""} | Set-Content test.txt

The meaning of individual commands:

  • Get-Content - reads content of a file.
  • Where-Object (? is alias) - filters content and removes empty lines.
  • Set-Content - replaces existing content in a file.

Leave a Comment

Cancel reply

Your email address will not be published.