For some time no I have to remove empty (white) lines from a text file or an array.
Here’s the function I wrote that I would like to share with you… I hope you’ll find it useful 🙂
You can use it like so:
$array = ‘a’,’b’,”,’c’,’d’,”,”,’e’
$Array | Remove-EmptyLines
Remove-EmptyLines -InputObject $array
Remove-EmptyLines -InputObject (Get-Content myfile.txt)
Get-Content myfile.txt | Remove-EmptyLines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function Remove-EmptyLines { <# .SYNOPSIS Remove the empty lines from an array. .DESCRIPTION A PowerShell function to remove the empty lines from an array. .EXAMPLE $array = 'a','b','','c','d','','','e' $Array | Remove-EmptyLines .EXAMPLE Remove-EmptyLines -InputObject (Get-Content Myfile.txt) .NOTES Author : Jeff Wouters Date : 16th of April 2014 #> [cmdletbinding()] param ( [parameter(mandatory=$true,position=0,ValueFromPipeline=$true)][array]$InputObject ) begin { } process { $InputObject.split('',[System.StringSplitOptions]::RemoveEmptyEntries) } end { } } |
Much appreciated for sharing!
Works like a charm;
in contrary to the often seen and not functioning
(gc file.txt) | ? {$_.trim() -ne “” } | set-content file.txt
Cheers
Harro