remove empty lines from text file with PowerShell

后端 未结 11 1751
情话喂你
情话喂你 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 19:59

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

    0 讨论(0)
  • 2020-12-08 19:59

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

    0 讨论(0)
  • 2020-12-08 19:59

    file

    PS /home/edward/Desktop> Get-Content ./copy.txt

    [Desktop Entry]

    Name=calibre Exec=~/Apps/calibre/calibre

    Icon=~/Apps/calibre/resources/content-server/calibre.png

    Type=Application*


    Start by get the content from file and trim the white spaces if any found in each line of the text document. That becomes the object passed to the where-object to go through the array looking at each member of the array with string length greater then 0. That object is passed to replace the content of the file you started with. It would probably be better to make a new file... Last thing to do is reads back the newly made file's content and see your awesomeness.

    (Get-Content ./copy.txt).Trim() | Where-Object{$_.length -gt 0} | Set-Content ./copy.txt

    Get-Content ./copy.txt

    0 讨论(0)
  • 2020-12-08 20:02

    This removes trailing whitespace and blank lines from file.txt

    PS C:\Users\> (gc file.txt) | Foreach {$_.TrimEnd()} | where {$_ -ne ""} | Set-Content file.txt
    
    0 讨论(0)
  • 2020-12-08 20:03
    (Get-Content c:\FileWithEmptyLines.txt) | 
        Foreach { $_ -Replace  "Old content", " New content" } | 
        Set-Content c:\FileWithEmptyLines.txt;
    
    0 讨论(0)
  • 2020-12-08 20:04

    To resolve this with RegEx, you need to use the multiline flag (?m):

    ((Get-Content file.txt -Raw) -replace "(?m)^\s*`r`n",'').trim() | Set-Content file.txt
    
    0 讨论(0)
提交回复
热议问题