Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove empty lines from text file with PowerShell

I know that I can use:

gc c:\FileWithEmptyLines.txt | where {$_ -ne ""} > c:\FileWithNoEmptyLines.txt 

to remove empty lines. But How I can remove them with '-replace' ?

like image 708
Suliman Avatar asked Feb 10 '12 06:02

Suliman


People also ask

How do I remove spaces from a text file in PowerShell?

We can use following script to remove space at the end of each line in a file with the help of powershell script. $InputFile = 'C:\Users\user\Desktop\1. txt' write-host "removing trailing space.. of file $InputFile" $content = Get-Content $InputFile $content | Foreach {$_. TrimEnd()} | Set-Content newfile.

How do I remove trailing spaces in PowerShell?

You want to remove leading or trailing spaces from a string or user input. Use the Trim() method of the string to remove all leading and trailing whitespace characters from that string. The Trim() method cleans all whitespace from the beginning and end of a string.

Which is the right command to search blank lines in a file?

To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use an extended regular expression like ' a^ ' or ' $a '.

How do I get the content of a file in PowerShell?

The Get-Content cmdlet gets the content of the item at the location specified by the path, such as the text in a file or the content of a function. For files, the content is read one line at a time and returns a collection of objects, each of which represents a line of content.


1 Answers

I found a nice one liner here >> http://www.pixelchef.net/remove-empty-lines-file-powershell. Just tested it out with several blanks lines including newlines only as well as lines with just spaces, just tabs, and combinations.

(gc file.txt) | ? {$_.trim() -ne "" } | set-content file.txt 

See the original for some notes about the code. Nice :)

like image 69
Randy Skretka Avatar answered Oct 11 '22 09:10

Randy Skretka