PowerShell: How to Remove Empty Lines from a File


Often you may want to use PowerShell to remove all empty lines from a specific file.

You can use the following syntax to do so:

(gc data.txt) | ? { -not [String]::IsNullOrWhiteSpace($_) } | sc data.txt

This particular example removes all empty lines from the text file named data.txt.

Here is what the various commands do:

  • gc: This is an alias for the Get-Content cmdlet and retrieves all lines from the file named data.txt.
  • ?: This is an alias for the Where-Object cmdlet and allows us to filter based on a condition.
  • -not [String]::IsNullOrWhiteSpace($_): Specifies that we want to filter the file for only the lines that are not null or simply contain whitespace.
  • sc: This is an alias for the Set-Content cmdlet and it saves the changes made to the original file.

The following example shows how to use this syntax in practice.

Example: How to Remove Empty Lines from a File in PowerShell

Suppose we have a file named data.txt in our current directory that contains information about various basketball players.

We can use the Get-Content cmdlet to view the contents of this file:

Notice that there are several empty lines in the file.

Now suppose that we would like to remove all of these empty lines from the file.

We can use the following syntax to do so:

(gc data.txt) | ? { -not [String]::IsNullOrWhiteSpace($_) } | sc data.txt

The following screenshot shows how to use this syntax in practice:

PowerShell remove empty lines from a file

Notice that when we use the Get-Content cmdlet to view the updated contents of the file named data.txt we can see that all empty lines have been removed from the file.

Note: If you would like to save these changes to a new file without modifying the original file, simply change the name of the file used after the sc (Set-Content) command.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Remove Lines Containing Specific String
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply