PowerShell Script to Remove Blank Lines from File
Get-Content input.txt | Where-Object { $_.Trim() -ne '' } | Set-Content output.txt to remove blank lines from a file in PowerShell.Examples
How to Think About It
Trim(), then keep only those lines and write them back to a file.Algorithm
Code
Get-Content input.txt | Where-Object { $_.Trim() -ne '' } | Set-Content output.txt
Write-Output "Blank lines removed and saved to output.txt"Dry Run
Let's trace the input file with lines: 'Line 1', '', 'Line 3', '', '', 'Line 6' through the code.
Read lines
["Line 1", "", "Line 3", "", "", "Line 6"]
Filter non-blank lines
Keep lines where Trim() is not empty: ["Line 1", "Line 3", "Line 6"]
Write output
Write filtered lines to output.txt
| Original Line | Trimmed Line | Keep? |
|---|---|---|
| Line 1 | Line 1 | Yes |
| No | ||
| Line 3 | Line 3 | Yes |
| No | ||
| No | ||
| Line 6 | Line 6 | Yes |
Why This Works
Step 1: Read file lines
The Get-Content command reads the file line by line into an array.
Step 2: Filter blank lines
The Where-Object filters lines where Trim() removes spaces and checks if the line is not empty.
Step 3: Save filtered lines
The filtered lines are saved back to a file using Set-Content.
Alternative Approaches
$content = Get-Content input.txt -Raw $content -replace '^(\s*\r?\n)+', '' | Set-Content output.txt Write-Output "Blank lines removed using -replace"
Get-Content input.txt | ForEach-Object { if ($_.Trim() -ne '') { $_ } } | Set-Content output.txt
Write-Output "Blank lines removed using ForEach-Object"Complexity: O(n) time, O(n) space
Time Complexity
The script reads each line once and filters it, so time grows linearly with the number of lines.
Space Complexity
All lines are stored in memory during processing, so space grows linearly with file size.
Which Approach is Fastest?
The pipeline with Where-Object is efficient and readable; regex approach uses more memory but can be faster for small files.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Where-Object filter | O(n) | O(n) | Large files, readability |
| -replace regex | O(n) | O(n) | Small files, regex familiarity |
| ForEach-Object condition | O(n) | O(n) | Explicit control, clarity |
Trim() to remove spaces before checking if a line is blank.Trim() causes lines with spaces to be treated as non-blank.