合并CSV,匹配不同格式的列

时间:2016-01-22 21:15:46

标签: csv powershell

我有两个CSV,第一个格式如下:

Campus ID,Student ID,Grade,Last Name,First Name,Active
1,50000,12,TEST,USER,1
1,600000,12,EXAMPLE,USER,1

然后我需要合并另一个CSV:

Name,E-Mail Address
User Test,30TestU@example.com
User Example,40ExampleU@example.com

我需要合并或创建一个新CSV,将第一个CSV中的名字和列名列与第二个CSV中的名称列相匹配,然后添加另一个列和匹配用户的电子邮件地址。我不需要保留第二个CSV中的名称。

例如,结果如下所示:

Campus ID,Student ID,Grade,Last Name,First Name,Active,Email
1,50000,12,TEST,USER,1,30TestU@example.com
1,600000,12,EXAMPLE,USER,1,40ExampleU@example.com

我已经尝试使用PowerShell,并且能够获得额外的列,但匹配名称,因为它们是不同的格式有点太多了。我不需要PowerShell,如果效果更好,我可以使用其他东西。

1 个答案:

答案 0 :(得分:0)

这是一个解决方案,但我永远不会使用它,因为如果多个用户具有相同的名称,它只会选择第一个匹配。而单一的更改(错误或可能是中间名称)会破坏它。

<# Sample One
$one = @"
Campus ID,Student ID,Grade,Last Name,First Name,Active
1,50000,12,TEST,USER,1
1,600000,12,EXAMPLE,USER,1
"@ | ConvertFrom-Csv
#>

$one = Import-Csv SampleOne.csv

<# Sample two
$two = @"
Name,E-Mail Address
User Test,30TestU@example.com
User Example,40ExampleU@example.com
"@ | ConvertFrom-Csv
#>

$two = Import-Csv SampleTwo.csv

$three = $one | ForEach-Object {
    $name = $_."First Name" + " " + $_."Last Name"
    $email = $two | Where-Object { $_.Name -eq $name } | Select-Object -First 1 -ExpandProperty "E-Mail Address"
    $_ | Add-Member -MemberType NoteProperty -Name Email -Value $email -PassThru
}

$three |
Select-Object "Campus ID","Student ID","Grade","Last Name","First Name","Active","Email" |
Export-Csv -Path Out.csv -NoTypeInformation

输出:

"Campus ID","Student ID","Grade","Last Name","First Name","Active","Email"
"1","50000","12","TEST","USER","1","30TestU@example.com"
"1","600000","12","EXAMPLE","USER","1","40ExampleU@example.com"