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' ?
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.
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.
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 '.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With