繁体   English   中英

在不改变列顺序的情况下将两个 CSV 文件合并到 powershell 中

[英]Combine two CSV files in powershell without changing the order of columns

我有“a.csv”和“b.csv”。 我试图将它们与以下命令合并

cd c:/users/mine/test 
Get-Content   a.csv, b.csv |  Select-Object -Unique | Set-Content -Encoding ASCII joined.csv

但是我得到了 Output 文件,例如 b.csv 文件添加到 a.csv 行的末尾。 我想在 a.csv 列的末尾添加,然后 b.csv 列应该开始

Vm     Resource    SID
mnvb    vclkn     vxjcb
vjc.v   vnxc,m    bvkxncb

Vm      123     456     789
mnvb   apple    banana  orange 
vjc.v  lemon    onion   tomato

我预期的 output 应该如下所示。 不改变顺序

Vm     Resource    SID    123       456     789
mnvb    vclkn   vxjcb     apple    banana  orange 
vjc.v   vnxc,m  bvkxncb   lemon    onion   tomato

这里开始,有两种方法-

加入对象自定义 function 由 RamblingCookieMonster。 这是简短而甜蜜的。 在您当前的 PoSh 环境中导入 function 后,您可以使用以下命令来获得您想要的结果 -

Join-Object -Left $a -Right $b -LeftJoinProperty vm -RightJoinProperty vm | Export-Csv Joined.csv -NTI

mklement接受的答案对您有用,如下所示 -

# Read the 2 CSV files into collections of custom objects.
# Note: This reads the entire files into memory.
$doc1 = Import-Csv a.csv
$doc2 = Import-Csv b.csv

$outFile = 'Joined.csv'

# Determine the column (property) names that are unique to document 2.
$doc2OnlyColNames = (
  Compare-Object $doc1[0].psobject.properties.name $doc2[0].psobject.properties.name |
    Where-Object SideIndicator -eq '=>'
).InputObject

# Initialize an ordered hashtable that will be used to temporarily store
# each document 2 row's unique values as key-value pairs, so that they
# can be appended as properties to each document-1 row.
$htUniqueRowD2Props = [ordered] @{}

# Process the corresponding rows one by one, construct a merged output object
# for each, and export the merged objects to a new CSV file.
$i = 0
$(foreach($rowD1 in $doc1) {
  # Get the corresponding row from document 2.
  $rowD2 = $doc2[$i++]
  # Extract the values from the unique document-2 columns and store them in the ordered
  # hashtable.
  foreach($pname in $doc2OnlyColNames) { $htUniqueRowD2Props.$pname = $rowD2.$pname }
  # Add the properties represented by the hashtable entries to the
  # document-1 row at hand and output the augmented object (-PassThru).
  $rowD1 | Add-Member -NotePropertyMembers $htUniqueRowD2Props -PassThru
}) | Export-Csv -NoTypeInformation -Encoding Utf8 $outFile

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM