当前位置: 动力学知识库 > 问答 > 编程问答 >

powershell to compare 2 csv files and where a duplicate fields the rest of the row is updated

问题描述:

This is difficult to explain, but I will try my best.

I have 2 CSV files called file1.csv and file2.csv...

What I would like is for file1.csv to try and match entries in its first column to entries in the first column of the file2.csv. If a match exists then I want the row from File1.csv to overwrite that particular row in file2.csv. I don't mind if it outputs to another file. Please help :)

File1:

uniqueID, first, surname, address

1, Joe, Bloggs, 32 Cheddar Rd

2, Bill, Gates, 21 SOmewhere Road

3, Tim, Burton, 24 This Lane

File2:

uniqueID, first, surname, address

1, Joe, Bloggs, 34 BLAH BLAH

2, Bill, Gates, 43 BLAH BLAH

3, Tim, Burton, 65 BLAH BLAH

4, Kai, Peters, 42 BLAH BLAH

5, Gay, Thomas, 65 BLAH BLAH

Output:

uniqueID, first, surname, address

1, Joe, Bloggs, 32 Cheddar Rd

2, Bill, Gates, 21 SOmewhere Road

3, Tim, Burton, 24 This Lane

4, Kai, Peters, 42 BLAH BLAH

5, Gay, Thomas, 65 BLAH BLAH

Thanks

Spencer

网友答案:

You should show some code of what you tried to get help, but since this is your first post I'll help you along.

$file1 = Import-Csv file1.txt
$file2 = Import-Csv file2.txt

$file2 | % {$Entry = $_; $file1 | ? {$_.uniqueID -eq $Entry.uniqueID} | % {$Entry.address = $_.address}}

$Results = @()

$file2  | % {$Results += New-Object -TypeName PSObject -Property @{"uniqueID" = $_.uniqueID; "first" = $_.First; "surname" = $_.surname; "address" = $_.address} }

$Results | Export-Csv -Path file3.csv -NoTypeInformation
分享给朋友:
您可能感兴趣的文章:
随机阅读: