45

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

2
  • 3
    Why do you want to replace? And work on your acceptance rate Commented Feb 10, 2012 at 6:09
  • 1
    My answer removes empty lines with the -replace comparison operator. Get-Content doesn't have a replace parameter, so I'm assuming you're looking for a way to do it with the operator. Commented Feb 10, 2012 at 7:47

13 Answers 13

84

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

Sign up to request clarification or add additional context in comments.

3 Comments

I think on balance I prefer (gc file.txt) | ? { -not $_.IsNullOrWhiteSpace() } | set-content file.txt because it expresses the intent more clearly, but it amounts to the same thing.
On brief glance, I do not seem to have the "IsNullOrWhiteSpace()" method on my strings...and...how could an instance method check for null? The posted answer works great though!
The IsNullOrWhiteSpace is a static method from System.String object the proper way to call it in PowerShell is as follow : [String]::IsNullOrWhiteSpace({your string}). The correct command line base on Neil Barnwell comment is as follow: (gc file.txt) | ? { -not [String]::IsNullOrWhiteSpace($_) } | set-content file.txt
26

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)

Comments

9

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

Comments

6

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

1 Comment

This worked like charm. I was attempting to remove VB6 comments from a file and this was the final command I used - (Get-Content -Path ".\vbXML.cls") -replace "\'.*$", "" -notmatch "^\s*$" | Out-File ".\vbXML.uncommented.cls" -Append
3

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

Comments

1

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

3 Comments

is the Poowershell support -remove "" to remove emply lines?
No it's seems that it does not have support of "-remove".
You're talking apples and oranges. Remove and Replace are clearly different. What you have will basically work, but perhaps you are trying to rebuild the existing file but without the blanks. PS C:\> $text=get-content a.txt PS C:\> $text | where {$_} | out-file a.txt
1

This removes trailing whitespace and blank lines from file.txt

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

Comments

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

Comments

1

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

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

Comments

1

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

1 Comment

>to fix the wrongness of ~/ path to the full path as this file should have here is a bonus (Get-Content ./copy.txt).Replace("~/","/home/edward/") | Set-Content ./copy.txt
1
Set-Content -Path "File.txt" -Value (get-content -Path "File.txt" | Select-String -Pattern '^\s*$' -NotMatch)  

This works for me, originally got the line from here and added Joel's suggested '^\s*$': Using PowerShell to remove lines from a text file if it contains a string

Comments

0

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"

Comments

0

Get-Content returns immutable array of rows. You can covert this to mutable array and delete neccessary lines by index.Particular indexex you can get with match. After that you can write result to new file with Set-Content. With this approach you can avoid empty lines that powershell replace tool leaves when you try to replace smthing with "". Note that I dont guarantee perfect perfomance. Im not a professional powershell developer))

$fileLines = Get-Content $filePath
$neccessaryLine = Select-String -Path  $filePath -Pattern 'something'
if (-Not $neccessaryLine) { exit }
$neccessaryLineIndex = $neccessaryLine.LineNumber - 1
$updatedFileContent = [System.Collections.ArrayList]::new($fileLines)
$updatedFileContent.RemoveAt($neccessaryLineIndex)
$updatedHostsFileContent.RemoveAt($domainInfoLineIndex - 1)
$updatedHostsFileContent | Set-Content $hostsFilePath

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.