Table of Contents
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.
1 2 3 |
Get-Content sample.txt |
Output:
1 2 3 4 5 6 7 |
This is a first line. This is a second line. This is a third line. |
As you can see, the file has multiple empty lines. To filter and remove empty lines, execute the command below.
1 2 3 |
Get-Content sample.txt | ? {$_ -ne ""} |
Output:
1 2 3 4 5 |
This is a first line. This is a second line. This is a third line. |
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.
1 2 3 |
Get-Content sample.txt | ? {$_ -ne ""} | Out-File newsample.txt |
Verify the content in a new file.
1 2 3 |
Get-Content newsample.txt |
Output:
1 2 3 4 5 |
This is a first line. This is a second line. This is a third line. |
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.
1 2 3 |
Get-Content sample.txt | ? {$_.trim() -ne ""} | Out-File newsample.txt |
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.
1 2 3 |
(Get-Content sample.txt) | ? {$_.trim() -ne ""} | Out-File sample.txt |
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.
1 2 3 |
((Get-Content sample.txt.txt -Raw) -replace "(?m)^\s*`r`n",'').trim() | Set-Content newsample.txt |
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*r
n
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.