user11708158
user11708158

Reputation:

How to merge two csv files by keeping the duplicate column name in Powershell

I have "a.csv" and "b.csv" . I tried to merge them with below commands

cd c:/users/mine/test 
Get-Content   a.csv, b.csv |  Select-Object -Unique | Set-Content -Encoding ASCII joined.csv

But I got Output file like b.csv added by end of the row of a.csv. I wanted add by end of the column of a.csv then b.csv columns should begin Note:- I cant install Join-Object module in my server.

Vm     Resource    SID
mnvb    vclkn     vxjcb
vjc.v   vnxc,m    bvkxncb

Vm      123     456     789
b      apple    banana  orange 
v      lemon    onion   tomato

My expected output should be like below. Without changing the order and keeping Vm column name without over writing

Vm     Resource    SID   Vm   123      456  789
mnvb    vclkn   vxjcb    b   apple    banana  orange 
vjc.v   vnxc,m  bvkxncb  v   lemon    onion   tomato

Upvotes: 2

Views: 289

Answers (1)

iRon
iRon

Reputation: 23663

This Join-Object is based on script rather than a module, this means that you might first "install" (download) it on another machine and that just copy/paste it (or the contents) to your server. You might also download it from the project site and dot-source the script: . .\Join-Object.ps1.
See also: In Powershell, what's the best way to join two tables into one?.

Specific to your question:
As @Theo commented "Duplicate column names is a bad thing in csv", especially in PowerShell where a ConvertFrom-Csv cmdlet will cause an error on such a csv file.
The Join-Object script has although a possibility to join object based on the row index by simply omitting the -On parameter. In that case it will put columns that exist on both sides in an array by default:

Import-Csv a.csv | Join-Object (Import-Csv b.csv) | Format-Table

Vm         Resource SID     123   456    789
--         -------- ---     ---   ---    ---
{mnvb, b}  vclkn    vxjcb   apple banana orange
{vjc.v, v} vnxc,m   bvkxncb lemon onion  tomato

By using the -Discern parameter, Join-Object spits the duplicate values over two columns using the discern values as prefixes:

Import-Csv a.csv | Join-Object (Import-Csv b.csv) -Discern a,b | Format-Table

aVm   Resource SID     bVm 123   456    789
---   -------- ---     --- ---   ---    ---
mnvb  vclkn    vxjcb   b   apple banana orange
vjc.v vnxc,m   bvkxncb v   lemon onion  tomato

Upvotes: 2

Related Questions