在Powershell中合并2个CSV文件 [英] Merge 2 csv files in powershell
问题描述
我有2个csv文件,我想从文件A到文件B的新列添加到新文件. Atm,它不采用A中的值.
I have 2 csv files, I want to add a new column from file A to file B to a new file. Atm, It doesn't take the values from A.
文件A.csv
ID Name
1 Peter
2 Dalas
文件B.CSV
Class
Math
Physic
新文件将是:
ID Name Class
1 Peter Math
2 Dalas Physics
两个文件的行数相同.
作为下面我正在使用的代码,我现在想如何从文件A中获取值并将其放入文件B中.
As the following the code I'm using, I would like to now how to take the values from file A and put it in file B.
$CSV1 = Import-Csv ".\A.csv"
$CSV2 = Import-Csv ".\B.csv"
$CSV1 | ForEach-Object {
$Value= $_
$CSV2 | Select-Object *, @{Name='Information';Expression={ $Value}}
} | Export-Csv "C.csv" -NoTypeInformation
推荐答案
假定您的两个CSV文件正确对齐(例如,您要基于它们的行号合并数据,并且不通过其他任何键进行链接),建议以下内容:
Assuming that your two CSV files are correctly aligned (e.g you want to merge the data based on their row numbers and aren't linking by any other key) I suggest the following:
$CSV1 = Import-Csv ".\A.csv"
$CSV2 = Import-Csv ".\B.csv"
$CSV1 | ForEach-Object -Begin {$i = 0} {
$_ | Add-Member -MemberType NoteProperty -Name 'Class' -Value $CSV2[$i++].Class -PassThru
} | Export-Csv "C.csv" -NoTypeInformation
说明:
- 使用
-Begin
脚本块将计数器设置为0(您可以在ForEach-Object
之前执行此操作,但使用-Begin
可以将其目的很好地链接到代码块). - 使用Add-Member在CSV2中的每一行上使用CSV2中的行的Array索引(并像在
++
中那样增加该索引),将'Class'属性添加到CSV1中的每一行. - 使用
-PassThru
开关将对象返回到管道.
- Uses a
-Begin
script block to set a counter to 0 (you could do this before theForEach-Object
but using-Begin
nicely links its purpose to the code block). - Uses Add-Member to add the 'Class' property to each line in CSV1, using the Array index of the line in CSV2 (and incrementing that index as it does it with
++
). - Uses the
-PassThru
switch to return the object to the pipeline.
如果您想以另一种方式(B> A)进行操作,则可以采用相同的方法,但是需要这样做:
If you want to do it the other way around (B > A) you could take the same approach but would need to do it like this:
$CSV2 | ForEach-Object -Begin {$i = 0} {
$CSV1[$i++] | Add-Member -MemberType NoteProperty -Name 'Class' -Value $_.Class -PassThru
} | Export-Csv "C.csv" -NoTypeInformation
实际上我很惊讶$_.Class
仍然可以像新管道的另一端一样工作,但是似乎可以.
I'm actually surprised $_.Class
still works as its the other side of a new pipeline but it seems to.
您还可以像最初计划的那样使用计算表达式,但是由于额外的管道,您确实需要使用额外的变量来存储$Class
:
You can also use a calculated expression like you originally planned to, but then you do need to use an extra variable to store $Class
due to the extra pipeline:
$CSV2 | ForEach-Object -Begin {$i = 0} {
$Class = $_.Class
$CSV1[$i++] | Select @{Name='Class';Expression={$Class}},*
} | Export-Csv "C.csv" -NoTypeInformation
这篇关于在Powershell中合并2个CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!