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

标签 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"

will become

"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"

The line I have in my script replaces ALL - in the csv .. even the Name column :-(

(Get-Content $ImportCPUFile) | % {$_ -replace "-"} | out-file -FilePath CSV-cleaned.csv -Fo -En ascii

最佳答案

尝试这样的事情:

$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 '-' 进行比较。

关于PowerShell - 替换 csv 文件中特定列中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43188493/

相关文章:

MySQL 防止小数字段四舍五入

mysql - 使用sed解析文本文件以生成CSV文件

windows - 如何捕获由另一个 cmd 窗口生成的 cmd 窗口的输出?

azure - 让 Azure 存储在列出存储容器内容时返回 blob URL

powershell - 系统找不到指定的文件 - 任务计划程序

powershell - PowerShell 的 Get-ChildItem cmdlet 返回的可能的 'Mode' 值是什么?

regex - 如何对 2 列 CSV/Notepad++ 数据进行排序?

javascript - google Apps 脚本中的 createFile() 无法正常运行

python - 使用 dictreader 时重命名标题

powershell - 在PowerShell中共享文件夹并设置权限