Reputation: 579
Recently this question was posted on stackoverflow, I have a similar problem as J. Williams except I only need to remove empty lines (removing spaces would not hurt the program though, it just isn't necessary). When I tried his original as well as the solution compo gave it only cleared the file instead of removing extra lines. I'm using it by itself in a batch file.
Example: I need this:
Joe
Bob
Mark
Frank
Dutch
(blank line here too)
to become this:
Joe
Bob
Mark
Frank
Dutch
I'm open to attaching such a solution to this powershell script too, as it is what is giving me the blank lines: (Get-Content friends.txt) | Where-Object {$_ -notmatch "\bJoe\b"} | Set-Content friends.txt
Thank's for your help.
Upvotes: 1
Views: 7414
Reputation: 10034
Another PowerShell method would be to use the Select-String
cmdlet using the regex pattern .+
which means one or more of any character. Also if using Set-Content
be sure to use the -NoNewLine
parameter to prevent the unwanted blank line at the end. (Requires PS5+)
(Select-String -Path C:\example.txt -Pattern '.+' |
Select-Object -ExpandProperty line) -join [Environment]::NewLine |
Set-Content C:\exampleoutput.txt -NoNewline
Upvotes: 0
Reputation: 1870
This should work for you - in short, it reads all the lines of the file, then writes back only the lines with something in it to the file.
$friends = Get-Content friends.txt
$friends | Where-Object { $_ } | Set-Content friends.txt
Upvotes: 4
Reputation: 68243
If it's a relatively small file:
(Get-Content $infile) -match '\S' | Set-Content $infile
If it's too large to read into memory all at once:
Get-Content $infile -ReadCount 1000 |
ForeachObject {
$_ -match '\S' |
Add-Content $outfile
}
Upvotes: 3