Created
December 11, 2015 08:48
-
-
Save vermorel/df1115e3e1a76dfbedaa to your computer and use it in GitHub Desktop.
CrossJoin-Csv, cartesian product on flat files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Cross-Join between two flat files | |
# By Joannes Vermorel, 2015-12-11 | |
# | |
# Syntax: | |
# Crossjoin-Csv .\sample.csv .\sample.csv "Name" | |
function Crossjoin-Csv | |
{ | |
param | |
( | |
[string] $file1, | |
[string] $file2, | |
[string] $pivot | |
) | |
# adjusting the delimiter automatically | |
if($file1.ToLower().EndsWith(".tsv")) | |
{ | |
$t1 = Import-Csv -Delimiter "`t" $file1; | |
} | |
else | |
{ | |
$t1 = Import-Csv $file1; | |
} | |
if($file2.ToLower().EndsWith(".tsv")) | |
{ | |
$t2 = Import-Csv -Delimiter "`t" $file2; | |
} | |
else | |
{ | |
$t2 = Import-Csv $file2; | |
} | |
$lookup = $t2 | Group-Object -AsHashTable -AsString -Property $pivot; | |
$f1 = $t1 | Get-Member | Where-Object {$_.MemberType -eq "NoteProperty"} | Foreach-Object{$_.Name}; | |
$f2 = $t2 | Get-Member | Where-Object {$_.MemberType -eq "NoteProperty"} | Foreach-Object{$_.Name} | Where-Object{$_ -ne $pivot}; | |
# writing the fields for the first line | |
($f1 + $f2) | & {$ofs=',';"$input"}; | |
Foreach($a in $t1) | |
{ | |
Foreach($b in $lookup[$a.$pivot]) | |
{ | |
(($f1 | ForEach-Object{$a.$_}) + ($f2 | ForEach-Object{$b.$_})) | & {$ofs=',';"$input"}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment