You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell删除CSV中第6列为空的行

移除CSV中第6列为空行的PowerShell脚本解决方案

问题场景

有一个无表头的CSV文件,内容示例如下:

"88212526";"Starter";"PowerMax";"4543";"5713852369748";"146,79";"EUR";"6"
"88212527";"Starter";"PowerMax";"4543";"5713852369755";"66,88";"EUR";"20"
"88212530";"Starter";"PowerMax";"4543";"5713852369786";"143,27";"EUR";"0"
"88212532";"Starter";"PowerMax";"4543";"5713852369809";"80,98";"EUR";"6"
"88212536";"Starter";"PowerMax";"4543";"5713852369847";"";"EUR";"0"
"88212542";"Starter";"PowerMax";"4543";"5713852369908";"77,16";"EUR";"9"
"88212543";"Starter";"PowerMax";"4543";"5713852369915";"77,46";"EUR";"52"

需求是删除第6列为空的整行,尝试了以下脚本但无效:

Foreach ($line in Get-Content .\POWERMAX_DK_1.csv) {
    $linearray = $line.split(";")
    if($linearray[6] -ne "") {
        Add-Content .\myTempFile.csv $line
    }
}

问题原因

  1. 索引错误:PowerShell数组索引从0开始,第6列对应的索引是5,而非6。
  2. 空值判断错误:CSV中空列的内容是""(带双引号的空字符串),直接判断-ne ""无法匹配,因为split后得到的元素是""而非空字符串。

解决方案

方法1:使用Import-Csv(推荐)

用PowerShell内置的CSV处理命令更可靠,指定分隔符为;并手动添加临时表头:

# 定义临时表头,对应8列数据
$headers = @("Col1","Col2","Col3","Col4","Col5","Col6","Col7","Col8")
# 导入CSV,过滤Col6不为空的行,再导出为新CSV
Import-Csv .\POWERMAX_DK_1.csv -Delimiter ";" -Header $headers | 
    Where-Object { $_.Col6 -ne "" } | 
    Export-Csv .\filtered_POWERMAX_DK_1.csv -Delimiter ";" -NoTypeInformation -Encoding UTF8

若不需要导出后的表头,可移除第一行:

Get-Content .\filtered_POWERMAX_DK_1.csv | Select-Object -Skip 1 | Set-Content .\final_POWERMAX_DK_1.csv -Encoding UTF8

方法2:修复原始脚本

调整索引并修正空值判断逻辑:

foreach ($line in Get-Content .\POWERMAX_DK_1.csv) {
    $linearray = $line.split(";")
    # 第6列是索引5,判断其是否不等于带引号的空字符串
    if ($linearray[5] -ne '""') {
        Add-Content .\myTempFile.csv $line
    }
}
# 替换原文件(可选)
# Move-Item .\myTempFile.csv .\POWERMAX_DK_1.csv -Force

内容的提问来源于stack exchange,提问作者Kim Jensen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:54:20