【问题标题】:PowerShell - Replace a character in a specific column in a csv filePowerShell - 替换 csv 文件中特定列中的字符
【发布时间】:2017-04-04 03:12:36
【问题描述】:

我需要在许多 csv 文件中将"-" 替换为""(什么都没有),除了Name 列,它可能包含我需要保留的- 字符。

例如:

"Name","timestamp","CPU|Demand (%)","CPU|Demand (%)(趋势)","CPU|Demand (%)(30 天预测)" "ZY02-LAB-WinMachine","2017 年 3 月 2 日 12:01:19 AM","-","38.07","-" "ZY02-LAB-WinMachine","2017 年 3 月 21 日 10:45:00 AM","40.55","-","-" "ZY02-LAB-WinMachine","2017 年 4 月 6 日上午 11:56:19","-","-","38.69" "ZY02-LAB-WinMachine","2017 年 4 月 6 日 12:11:19 PM","-","-","38.7"

会变成

"Name","timestamp","CPU|Demand (%)","CPU|Demand (%)(趋势)","CPU|Demand (%)(30 天预测)" "ZY02-LAB-WinMachine","2017 年 3 月 2 日 12:01:19 AM","","38.07","" "ZY02-LAB-WinMachine","2017 年 3 月 21 日 10:45:00 AM","40.55","","" "ZY02-LAB-WinMachine","2017 年 4 月 6 日 11:56:19 AM","","","38.69" "ZY02-LAB-WinMachine","2017 年 4 月 6 日 12:11:19 PM","","","38.7"

我在脚本中的行替换了 csv 中的 ALL - .. 甚至是 Name 列 :-(

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

【问题讨论】:

    标签: powershell csv


    【解决方案1】:

    试试这样的:

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

      • Génial :-) 工作完美... :-)
      【解决方案3】:

      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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-15
        • 2022-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多