如何将两个csv文件合并到第三个文件中,而不添加行和列

yxyvkwin  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(118)

我想将两个 * 结构相同 * 的CSV文件合并到第三个文件中,* 一个单元格 * 一个单元格 * 地填充,不添加任何行或列,每行由 * 分段符 * 分隔。到目前为止,每个文件中只有一列。

文件1.csv:

Header
(Row1)first string from File1
(Row2)second string from File1

文件2.csv:

Header
(Row1)first string from File2
(Row2)second string from File2

(预期输出)File3.csv

Header
 (Row1)first string from File1
  first string from File2
 (Row2)second string from File1
  second string from File2
  • 我不想要的 *(但总是得到):
Header
(Row1)first string from File1
(Row2)first string from File2
(Row3)second string from File1
(Row4)second string from File2

我真的在网上搜索了很多,但是都没有成功。如果有人有解决的办法,那将是一个很大的帮助!
我的代码(目前为止):

$thirdFile = @()
$firstFile = @(Import-Csv "Path\File1.csv")
$secondFile = @(Import-Csv "Path\File2.csv")
$MaxLength = [Math]::Max($firstFile.Length, $secondFile.Length)
for ($i = 0; $i -lt $MaxLength; $i++)
{ 
    $thirdFile+=$firstFile[$i]
    $thirdFile+=$secondFile[$i]
}
$thirdFile | Export-Csv "Path\File3.csv" -NoTypeInformation
ax6ht2ek

ax6ht2ek1#

看起来您想要合并每个项目的值,这些值之间用换行符分隔。
在这种情况下,您可以执行以下操作:

$firstFile  = @(Import-Csv "Path\File1.csv")
$secondFile = @(Import-Csv "Path\File2.csv")
$headers    = $firstFile[0].PsObject.Properties.Name
$maxRows    = [Math]::Max($firstFile.Count, $secondFile.Count)

$thirdFile = for ($i = 0; $i -lt $maxRows; $i++) {
    if ($i -ge $firstFile.Count) { $secondFile[$i] }
    elseif ($i -ge $secondFile.Count) { $firstFile[$i] }
    else {
        # use an ordered Hashtable to collect and merge the values in each field
        $row = [ordered]@{}
        foreach ($header in $headers) {
            $row[$header] = '{0}{1}{2}' -f $firstFile[$i].$header, [environment]::NewLine, $secondFile[$i].$header
        }
        # cast to PsCustomObject and output so it gets collected in variable $thirdFile
        [PsCustomObject]$row
    }
}

# show on screen
$thirdFile | Format-Table -AutoSize -Wrap

# export to file
$thirdFile | Export-Csv "Path\File3.csv" -NoTypeInformation

相关问题