2

I need to delete the empty rows at end of the CSV file using Powershell. I tried the below code This code only working to remove the line 7 and 8 in the below sample file image. But I need to delete rows 3,4,5,6,7 and 8. Only row 2 has data. Any suggestion would be appreciated. thank you.

enter image description here

$content = [System.IO.File]::ReadAllText("PPC.csv")
$content = $content.Trim()
[System.IO.File]::WriteAllText("PPC_1.csv", $content)
1
  • 2
    Could you tell us why aren't you using Import-Csv? Commented Jul 20, 2021 at 3:16

2 Answers 2

4

There were two sources that helped me out, Powershell - remove blank/empty rows from CSV file and this StackOverflow question to remove empty lines from text file.

Get-Content "test.csv" | Where { $_.Replace(",","").trim() -ne "" } | Out-File trimmed.csv

To be fair, this line assumes that you're always going to have commas as your separator and that a line consisting only of commas and whitespace would be considered empty. I hope this helps! I recommend looking at those links.

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

Comments

0

An Import-Csv/Export-Csv version which gives you more control over delimiters and (empty) quoted strings (as: "","",""):

Import-Csv .\Input.csv |Where-Object { $_.PSObject.Properties.Value -ne '' } |Export-Csv .\Output.Csv

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.