Remove Empty Lines from File in PowerShell

We can do several file operations using the PowerShell console. For example, creating a file, removing a file, copying and moving a file, displaying file content, etc.

While working with files, you may encounter a situation where you need to delete blank lines in a file. This tutorial will show you how to remove empty lines from file in PowerShell.

Using Get-Content cmdlet and ne operator

Suppose you have a text file sample.txt and you want to remove blank lines from it.

To view the file content in PowerShell, you can use the Get-Content cmdlet.

Output:

As you can see, the file has multiple empty lines. To filter and remove empty lines, execute the command below.

Output:

The command ? {$_ -ne ""} gets all lines which do not equal the empty string. As a result, the empty lines are not printed.

? is an alias for the Where-Object cmdlet that helps to select objects from a collection.

To save the output to a file, you can pipe the above command to the Out-File cmdlet.

This command removes empty lines from a sample.txt file and saves it to a newsample.txt file.

Verify the content in a new file.

Output:

Using Get-Content cmdlet and ne operator and trim() function

The above example does not delete empty lines that include only spaces, tabs or both. You can use the trim() method to remove blank lines containing spaces and tabs.

If you want to save the output in the same original file, you must close the Get-Content command with parenthesis () as shown below. It ensures the command gets finished before passing through the pipeline.

Using replace Operator

To remove empty lines from file:

  • Use Get-Content cmdlet to get content of the file.
  • Use replace operator to replace empty lines identified by regular expression (?m)^\s*rn with empty space.
We used Get-Content cmdlet to read the content of the file.

We used replace operator to replace empty lines with empty string.

Replace operator takes two arguments:

substring to find in given string : (?m)^\s*rn
replacement String for found String: empty string

That’s all you need to know about how to remove empty lines from a file in PowerShell. If you have any confusion, let us know in the comments.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *