1

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)
DAR
  • 47
  • 6

2 Answers2

3

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.

lizzydev
  • 116
  • 3
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
iRon
  • 20,463
  • 10
  • 53
  • 79