从CSV文件中对列进行分组,并连接另一列的值

时间:2016-06-30 03:40:13

标签: csv powershell

我刚刚开始使用PowerShell,无法在任何地方找到答案 尝试编写导入CSV文件的脚本并搜索文件以查看是否有相同的名称。如果名称相同,我想在同一行上一起写下所有这些值,只显示一次名称。

例如:

Name   Number    
Tom    1  
Tom    4  
Bill   3  
Dave   2  
Dave   5   
Dave   6  

使用此输出:

Tom- The number(s) associated with this person is/are: 1/4  
Bill- The number(s) associated with this person is/are: 3  
Dave- The number(s) associated with this person is/are: 2/5/6

2 个答案:

答案 0 :(得分:1)

像这样的管道应该完成这项工作

Import-Csv .\test.csv |   
  Group-Object Name |  
  Foreach-Object { 
    $nums = $_.Group.Number;
    "{0}- The number(s) associated with this person is/are: {1}" -f $_.Name, ($nums -join '/') 
  }

答案 1 :(得分:0)

不太优雅的版本

$Data = Import-Csv .\test.csv
$hash = @{}
$output = @()
foreach ($name in $data) {
$hash[$name.name] += $name.number+"/"
}
foreach ($key in $hash.Keys) {
$values = $hash[$key] -replace ("/$")
$output += "$key - The number(s) associated with this person is/are: $values"
}
$output