我想將兩個相同結構的 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
uj5u.com熱心網友回復:
看起來您想將每個專案的值組合在一起,中間用換行符分隔。
在這種情況下,您可以執行以下操作:
$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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517239.html
標籤:电源外壳CSV
