0

I have 2 csv files and have file1.column1, file1.column2, file2.column1, file2.column2. I would like to have out put like below

File1:

Column1, Column2
1,a
2,b
3,c

File2:

Column1, Column2
x, abc
y, def
z, ghi

Output I am expecting is: File3:

File1.column1, File2.column2
1, abc
2, def
3, ghi
Naveen
  • 3
  • 1
  • 1
    So, how should script decide which line join with which? By line number? If yes, then it is your *key field*. – user4003407 Dec 28 '18 at 19:46
  • 2
    Possible duplicate of [CMD or Powershell command to combine (merge) corresponding lines from two files](https://stackoverflow.com/questions/27233249/cmd-or-powershell-command-to-combine-merge-corresponding-lines-from-two-files) –  Dec 28 '18 at 20:14

2 Answers2

2

Other method:

#load files
$F1=import-csv "C:\temp\File1.txt"
$F2=import-csv "C:\temp\File2.txt"

#found max element count for 2 files
$Count=[System.Math]::Max($F1.Count, $F2.Count)

#print as you want
0..$Count | select @{N="File1.Column1"; E={$F1[$_].Column1}}, @{N="File2.Column2"; E={$F2[$_].Column2}}
Esperento57
  • 16,521
  • 3
  • 39
  • 45
1

@PetSerAl is correct, it appears that you want to merge these on the line number, i.e the index of each row. Here's a contrived example with custom objects, just replace $File1 and $File2 with the output from Import-Csv:

$File1 = @(
[PSCustomObject]@{
    Column1 = 1
    Column2 = "a"
}
[PSCustomObject]@{
    Column1 = 2
    Column2 = "b"
}
[PSCustomObject]@{
    Column1 = 3
    Column2 = "c"
}
)

$File2 = @(
    [PSCustomObject]@{
        Column1 = "x"
        Column2 = "abc"
    }
    [PSCustomObject]@{
        Column1 = "y"
        Column2 = "def"
    }
    [PSCustomObject]@{
        Column1 = "z"
        Column2 = "ghi"
    }
)

for ($i = 0; $i -lt $File1.Count; $i++ )
{
    [PSCustomObject]@{
        "File1.Column1" = $File1[$i].Column1
        "File2.Column2" = $File2[$i].Column2
    }
}
Matt McNabb
  • 362
  • 4
  • 15
  • Import-Csv or a here string piped to ConvertFrom-Csv seems easier/shorter to me. –  Dec 28 '18 at 20:21
  • Perfect. Thank you! – Naveen Dec 28 '18 at 20:50
  • 1
    @LotPings the two custom objects above were stand-ins for the csv data. The for loop is what I was actually demonstrating. I'd just wanted there to be something there so the OP could copy the full script out and have it work as-is. – Matt McNabb Dec 29 '18 at 04:19