2

How to delete a empty line in file?

When i searched for it , people are creating another file to move non empty lines like follows

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

Is there any way to delete the line in the source file itself?

2 Answers 2

4

Why can't you save it back to the same file? Split it into 2 lines:

$var = gc c:\PST\1.txt | Where {$_ -ne ""}
$var > c:\pst\1.txt
Sign up to request clarification or add additional context in comments.

2 Comments

If i tried it , it delete all the contents . Redirect operator will delete the file. If i use append >> redirect , it will end up in infinite loop and file size grows humungous
fyi, If you have a line that contains only a tab character (e.g "`t"), $_ -ne "" will not skip it
3

Skip lines that match a space, a tab or a line break:

(Get-Content c:\FileWithEmptyLines.txt) | `
  Where-Object {$_ -match '\S'} | `
   Out-File c:\FileWithEmptyLines.txt

UPDATE: for multiple files:

$file = Get-ChildItem -Path "E:\copyforbuild*xcopy.txt" 

foreach ($f in $file)
{ 
    (Get-Content $f.FullName) | `
      Where-Object {$_ -match '\S'} | `
       Out-File $f.FullName
}

4 Comments

buddy , i think you have missed a } . Please update it , I need to tick the answer after that
Thanks for the heads up, fixed. I had two where-object calls and a missing brace :)
buddy , when your solution is being executed with multiple files it fails .For ex: $File = Get-ChildItem -Path "E:\copyforbuild\*xcopy.txt" Foreach ($f in $File) { $var= Get-Content ($f) |` Where-Object {$_ -match '\S'} |` Out-File $f }. when i use split it two lines it works fine.
How about this: $File = Get-ChildItem -Path "E:\copyforbuild*xcopy.txt"; Foreach ($f in $File){ (Get-Content $f.FullName) | Where-Object {$_ -match '\S'} | Out-File $f.fullname }

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.