使用 Powershell 删除 csv 文件末尾的空行

delete empty rows at end of the csv file using Powershell

我需要使用 Powershell 删除 CSV 文件末尾的空行。我试过下面的代码 此代码仅用于删除下面示例文件图像中的第 7 行和第 8 行。但我需要删除第 3、4、5、6、7 和 8 行。只有第 2 行有数据。任何建议将不胜感激。谢谢。

$content = [System.IO.File]::ReadAllText("PPC.csv")
$content = $content.Trim()
[System.IO.File]::WriteAllText("PPC_1.csv", $content)

有两个来源帮助了我,Powershell - remove blank/empty rows from CSV file and this Whosebug question 从文本文件中删除空行。

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

公平地说,此行假定您始终将逗号作为分隔符,并且仅由逗号和空格组成的行将被视为空行。我希望这有帮助!我建议查看这些链接。

一个 Import-Csv/Export-Csv 版本,让您可以更好地控制分隔符和(空)引用字符串(如:"","",""):

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