Skip to content

Instantly share code, notes, and snippets.

@vermorel
Created December 11, 2015 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vermorel/df1115e3e1a76dfbedaa to your computer and use it in GitHub Desktop.
Save vermorel/df1115e3e1a76dfbedaa to your computer and use it in GitHub Desktop.
CrossJoin-Csv, cartesian product on flat files
# 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