Bentoy13
Bentoy13

Reputation: 4974

Copy one column into another

I have two csv files and I want to merge them in the following way. Both files have the same number of rows. I want to replace the content of the i-th column from the first file by the content of the j-th column from second file.

Here is a short example. First file contains:

col0 col1 col2 col3
0 1 2 3
1 2 3 4
2 3 4 5

Second file contains:

colA colB
4 5 
5 6
6 7

Let's say I want to copy colB into col3, so my first array should contain:

col0 col1 col2 col3
0 1 2 5
1 2 3 6
2 3 4 7

Let's call first table table_1 and second table table_2.

$table_1 = Import-Csv -Delimiter " " -Path .\file1.csv
$table_2 = Import-Csv -Delimiter " " -Path .\file2.csv

# `$table_1.col3 = $table_2.colB` # -> error
`$table_2.colB.CopyTo($table_1.col3,0)` # -> no error, does nothing

$table_1| Export-Csv -Path .\file1.csv -Delimiter " " -Encoding Oem -NoTypeInformation

Is there any easy mean to copy content of one column into another column, other than doing an explicit index-based for-loop?

Upvotes: 0

Views: 210

Answers (1)

rokumaru
rokumaru

Reputation: 1244

There is a way to use the "Zip" method of .Net.

If you use it directly, it becomes hard to read like this,

[Linq.Enumerable]::Zip($table_1, $table_2, [Func[Object, Object, Object]]{ param($t1, $t2) $t1.col3 = $t2.colB })

so you better wrap it with a function and use it.

function zip ($obj1, $obj2, $rs) { [Linq.Enumerable]::Zip($obj1, $obj2, [Func[Object, Object, Object]]$rs) }

$table_1 = Import-Csv -Delimiter " " -Path .\file1.csv
$table_2 = Import-Csv -Delimiter " " -Path .\file2.csv

zip $table_1 $table_2 { param($t1, $t2) $t1.col3 = $t2.colB }

$table_1 | Export-Csv -Path .\file1.csv -Delimiter " " -Encoding Oem -NoTypeInformation

Upvotes: 2

Related Questions