如何全球取代","用";"在CSV文件中?

时间:2015-07-10 16:24:04

标签: csv powershell

例如,以下csv文件。

123,"a,b,c",456

将成为

123,"a;b;c",456

以下代码生成一个空文件(test.txt)并且速度很慢。

Import-Csv file.csv | % {
    $r = @{}
    foreach($v in $_.PSObject.Properties) {
        if ($v.Value -like "*,*") {
            $r | Add-Member -MemberType NoteProperty -Name $v.Name -Value ($v.Value -replace ",",";")
        }
        else {
            $r | Add-Member -MemberType NoteProperty -Name $v.Name -Value ($v.Value)
        }
    }
} | Export-Csv test.txt

2 个答案:

答案 0 :(得分:1)

正则表达方式。

在与@ dc7a9163d9发表一些关于可能不属于原始交易的可能性的评论之后,以下代码做了两件事:

a)用CSV字段中的分号(;)替换逗号(,)。

b)在CSV字段中用单引号(')替换成对的双引号("")。

$cRows = Get-Content -Path "file.csv"
$cNewRows = @()
foreach ($sRow in $cRows) {
    $sRow = $sRow `
        -replace '(?:(?<!^|,|[^"]"|"{3})),(?:(?!"[^"]|"{3}|$))', ';' `
        -replace '(?:(?<!^|[,]+))""', "'" -replace '""', "'"
    $cNewRows += $sRow
}

$cNewRows | Out-File -FilePath "test.txt"

答案 1 :(得分:1)

您可以将代码简化为以下内容:

$csv = Import-Csv 'C:\path\to\file.csv'

$properties = $csv[0].PSObject.Properties.Name

$csv | % {
  foreach ($p in $properties) {
    $_.$p = $_.$p -replace ',', ';'
  }
  $_   # "passthru"
} | Export-Csv 'C:\path\to\test.txt' -NoType

只评估属性名称一次,也避免创建新对象并始终向其添加新成员。