按值“名称”合并2 CSV并合并Count(Powershell)

时间:2012-09-20 17:57:15

标签: powershell csv merge count

所以在momemt我正在寻找合并2个CSV文件的方法。

这是我的意思的一个例子:

CSV1

"Name","Count"
"Klaus","3"
"Hans","2"
"Gerhard","1"
"Nina","6"
"Julia","10"
"Caro","19"

CSV2

"Name","Count"
"Klaus","2"
"Hans","1"
"Gerhard","1"
"Nina","1"

现在如果我合并两者,输出/结果应为:

"Name","Count"
"Klaus","5"
"Hans","3"
"Gerhard","2"
"Nina","7"
"Julia","10"
"Caro","19"

我尝试了很多,但我从来没有过;我总是有错误的结果。有没有人知道如何做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用Group-Object(别名group)按Name属性对所有内容进行分组。然后你只需要总结组中每个人的Count属性。 Measure-Object(别名measure)会为您做总结。

$grouped = Import-Csv .\csv1.csv, .\csv2.csv | group Name
$combined = $grouped |%{ 
   New-Object PsObject -Prop @{ Name = $_.Name; Count = ($_.Group | measure -sum -prop Count).Sum }
}
$combined | Export-Csv .\combined.csv -NoType

答案 1 :(得分:0)

导入CSV文件并将每个文件转换为哈希表,然后找到常用名称:

$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