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

PowerShell 5处理CSV:填充空列并输出无BOM UTF-8文件

问题说明

在Windows系统使用PowerShell 5时,文件夹内有多份.csv文件的第二列(translation)为空,需要用同名且后缀为_column3.txt的文件数据填充该列。现有脚本可实现填充功能,但带重音字符及亚洲字符显示异常,需修改脚本使输出文件为无BOM的UTF-8格式。


示例文件

原CSV文件(firstfile.csv)

header1,translation,source
first,,"third"
one,,three

对应填充文件(firstfile_column3.txt)

source
second, fifth
two

预期输出文件(firstfileoutput.csv)

header1,translation,source
first,"second, fifth","third"
one,two,three

修改后的脚本

param(
    $SourceDir = $PWD,
    $OutDir = $PWD,
    $OutFileSuffix = "output" # 定义输出文件的后缀
)

# 获取源目录下所有CSV文件
$csvFiles = Get-ChildItem -Path $SourceDir -Recurse -Filter "*.csv"

foreach ($csvFile in $csvFiles) {
    # 构造对应_column3.txt文件的路径
    $column3FileName = "{0}_column3.txt" -f $csvFile.BaseName
    $column3FilePath = Join-Path -Path $SourceDir -ChildPath $column3FileName
    
    # 检查填充文件是否存在
    if (Test-Path $column3FilePath) {
        # 导入CSV文件,指定UTF-8编码避免读取乱码
        $primaryCsv = Import-Csv -Path $csvFile.FullName -Encoding UTF8
        
        # 读取填充文件,指定UTF-8编码并跳过表头行
        $column3Values = Get-Content $column3FilePath -Encoding UTF8 | Select-Object -Skip 1

        # 填充translation列
        for ($i = 0; $i -lt $primaryCsv.Count; $i++) {
            $primaryCsv[$i].translation = $column3Values[$i]
        }

        # 构造输出文件路径
        $outputFilePath = Join-Path -Path $csvFile.DirectoryName -ChildPath ("{0}{1}.csv" -f $csvFile.BaseName, $OutFileSuffix)

        # 用.NET方法输出无BOM的UTF-8文件(PowerShell 5的Export-Csv默认带BOM)
        $csvContent = $primaryCsv | ConvertTo-Csv -NoTypeInformation
        [System.IO.File]::WriteAllLines($outputFilePath, $csvContent, [System.Text.Encoding]::UTF8)
    }
    else {
        Write-Warning "未找到$($csvFile.Name)对应的_column3文件"
    }
}

修改关键点

  • 统一读取编码:给Import-Csv和Get-Content添加-Encoding UTF8参数,确保特殊字符在读取阶段就被正确解析,从源头避免乱码。
  • 替换输出方式:PowerShell 5自带的Export-Csv -Encoding UTF8会生成带BOM的文件,改用.NET的[System.IO.File]::WriteAllLines方法,配合[System.Text.Encoding]::UTF8直接生成无BOM的UTF-8文件,彻底解决特殊字符显示异常问题。

内容的提问来源于stack exchange,提问作者Edoardo Endrizzi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 18:57:43