PowerShell - 替换csv文件中特定列中的字符

时间:2017-04-03 15:24:08

标签: powershell csv

我需要在许多csv文件中替换"-"(无)"" Name-列,其中可能包含-个字符我需要保留

例如:

"Name","timestamp","CPU|Demand (%)","CPU|Demand (%) (Trend)","CPU|Demand (%) (30 days forecast)"
"ZY02-LAB-WinMachine","Mar 2, 2017 12:01:19 AM","-","38.07","-"
"ZY02-LAB-WinMachine","Mar 21, 2017 10:45:00 AM","40.55","-","-"
"ZY02-LAB-WinMachine","Apr 6, 2017 11:56:19 AM","-","-","38.69"
"ZY02-LAB-WinMachine","Apr 6, 2017 12:11:19 PM","-","-","38.7"

将成为

"Name","timestamp","CPU|Demand (%)","CPU|Demand (%) (Trend)","CPU|Demand (%) (30 days forecast)"
"ZY02-LAB-WinMachine","Mar 2, 2017 12:01:19 AM","","38.07",""
"ZY02-LAB-WinMachine","Mar 21, 2017 10:45:00 AM","40.55","",""
"ZY02-LAB-WinMachine","Apr 6, 2017 11:56:19 AM","","","38.69"
"ZY02-LAB-WinMachine","Apr 6, 2017 12:11:19 PM","","","38.7"

我的脚本中的行替换了csv中的所有Name ..甚至是(Get-Content $ImportCPUFile) | % {$_ -replace "-"} | out-file -FilePath CSV-cleaned.csv -Fo -En ascii 列: - (

sed

3 个答案:

答案 0 :(得分:3)

尝试这样的事情:

$Csv = Import-Csv -Path $ImportCPUFile;
$Headers = $Csv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name;

ForEach ($Record in $Csv) {
    foreach ($Header in $Headers) {
        if ($Record.$Header -eq '-') {
            $Record.$Header = [String]::Empty;
        }
    }
}

$Csv | Export-Csv -Path $OutputFile -NoTypeInformation;

如果您在某些字段中有前导或尾随空格,则可能需要使用$Record.$Header.Trim() -eq '-'进行比较。

答案 1 :(得分:2)

试试这个:

(Get-Content $ImportCPUFile) |
    ForEach-Object { $_ -replace '"-"', '""' } |
    Out-File -FilePath CSV-cleaned.csv -Force -Encoding ascii

答案 2 :(得分:0)

Bacon Bits有非常好的代码,但我认为它可以稍加修改。如果Name列的值为“ - ”,会发生什么?

$Csv = Import-Csv -Path $ImportCPUFile

$Headers = $Csv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name;

ForEach ($Record in $Csv) {
    foreach ($Header in $Headers) {
        if ($Header -ne "Name") {
             $Record.$Header = $Record.$Header.Replace("-","")
        }
    }
}
$Headers = $Csv | Get-Member -MemberType NoteProperty


$Csv | Export-Csv -Path $OutputFile -NoTypeInformation;