remove empty lines from text file with PowerShell

后端 未结 11 1752
情话喂你
情话喂你 2020-12-08 19:32

I know that I can use:

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

to remove empty lines. But How

相关标签:
11条回答
  • 2020-12-08 20:07

    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"
    
    0 讨论(0)
  • 2020-12-08 20:10

    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)
    
    0 讨论(0)
  • 2020-12-08 20:12

    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
    
    0 讨论(0)
  • 2020-12-08 20:14

    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
    
    0 讨论(0)
  • 2020-12-08 20:16

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

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

    0 讨论(0)
提交回复
热议问题