Remove last line from file with Powershell

后端 未结 5 988

I am using

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

to remove the empty lines that SSRS puts at the b

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 04:36

    When you read a file using Get-Content it streams each line down the pipe as a string. When Out-File (essentially what > is an alias for) gets these strings, it always appends a line terminator sequence. Try the following if the files are not too big:

    $text = [IO.File]::ReadAllText("c:\FileWithEmptyLinesAtEnd.txt")
    [IO.File]::WriteAllText("c:\FileWithEmptyLinesAtEnd.txt", $text.TrimEnd())
    

    This is the file before:

    14> fhex .\FileWithEmptyLinesAtEnd.txt
    
    Address:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F ASCII
    -------- ----------------------------------------------- ----------------
    00000000 73 65 72 76 65 72 31 2C 73 65 72 76 65 72 32 2E server1,server2.
    00000010 64 6F 6D 61 69 6E 2E 6C 6F 63 61 6C 2C 73 65 72 domain.local,ser
    00000020 76 65 72 33 0D 0A 20 20 20 20 20 20             ver3..
    

    and after:

    19> fhex .\FileWithEmptyLinesAtEnd.txt
    
    Address:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F ASCII
    -------- ----------------------------------------------- ----------------
    00000000 73 65 72 76 65 72 31 2C 73 65 72 76 65 72 32 2E server1,server2.
    00000010 64 6F 6D 61 69 6E 2E 6C 6F 63 61 6C 2C 73 65 72 domain.local,ser
    00000020 76 65 72 33                                     ver3
    

提交回复
热议问题