remove empty lines from text file with PowerShell

2019-01-24 02:03发布

问题:

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' ?

回答1:

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 :)



回答2:

This piece of code from Randy Skretka is working fine for me, but I had the problem, that I still had a newline at the end of the file.

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

So I added finally this:

$content = [System.IO.File]::ReadAllText("file.txt")
$content = $content.Trim()
[System.IO.File]::WriteAllText("file.txt", $content)


回答3:

You can use -match instead -eq if you also want to exclude files that only contain whitespace characters:

@(gc c:\FileWithEmptyLines.txt) -match '\S'  | out-file c:\FileWithNoEmptyLines


回答4:

Not specifically using -replace, but you get the same effect parsing the content using -notmatch and regex.

(get-content 'c:\FileWithEmptyLines.txt') -notmatch '^\s*$' > c:\FileWithNoEmptyLines.txt


回答5:

You can't do replacing, you have to replace SOMETHING with SOMETHING, and you neither have both.



回答6:

(Get-Content c:\FileWithEmptyLines.txt) | 
    Foreach { $_ -Replace  "Old content", " New content" } | 
    Set-Content c:\FileWithEmptyLines.txt;


回答7:

This will remove empty lines or lines with only whitespace characters (tabs/spaces).

[IO.File]::ReadAllText("FileWithEmptyLines.txt") -replace '\s+\r\n+', "`r`n" | Out-File "c:\FileWithNoEmptyLines.txt"


回答8:

This removes trailing whitespace and blank lines from file.txt

PS C:\Users\> (gc file.txt) | Foreach {$_.TrimEnd()} | where {$_ -ne ""} | Set-Content file.txt


回答9:

If you actually want to filter blank lines from a file then you may try this:

(gc $source_file).Trim() | ? {$_.Length -gt 0}