Merge 2 CSV by Value “Name” and merge Count (Powershell)

后端 未结 2 1827
礼貌的吻别
礼貌的吻别 2021-01-26 20:12

So at the momemt I\'m searching for a way to merge 2 CSV files.

Here is an example for what I mean:

CSV1

\"Name\",\"Count\"
\"Klaus\",\"3\"
\"Han         


        
2条回答
  •  盖世英雄少女心
    2021-01-26 20:54

    Import the CSV files and convert each to a hash table, then find the common names:

    $csv1 = Import-Csv -Path csv1.csv
    $csv2 = Import-Csv -Path csv2.csv
    
    $HashCSV1 = @{}
    $HashCSV2 = @{}
    $HashMerge = @{}
    
    foreach($r in $csv1)
    {
        $HashCSV1[$r.Name] = $r.Count
    }
    
    foreach($r in $csv2)
    {
        $HashCSV2[$r.Name] = $r.Count
    }
    
    foreach ($key in $HashCSV1.Keys) { 
        if ($HashCSV2.ContainsKey($key)) {
            $HashMerge[$key] = [int]$HashCSV1[$key] + [int]$HashCSV2[$key]
        } else {
            $HashMerge[$key] = $HashCSV1[$key]
        }
    }
    
    foreach ($key in $HashCSV2.Keys) { 
        if (-not $HashCSV1.ContainsKey($key)) {
            $HashMerge[$key] = $HashCSV2[$key]
        }
    }
    
    &{$HashMerge.getenumerator() |
      foreach {new-object psobject -Property @{Name = $_.name;Count=$_.value}}
      } | export-csv merge.csv -notype     
    

提交回复
热议问题