【问题标题】:Combine two CSV files in powershell without changing the order of columns在powershell中合并两个CSV文件而不改变列的顺序
【发布时间】:2020-05-04 14:51:29
【问题描述】:

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

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

但是我在 a.csv 行的末尾添加了像 b.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

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

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

【问题讨论】:

标签: powershell


【解决方案1】:

来自here,有两种方法-

Join-Object RamblingCookieMonster 的自定义函数。这是简短而甜蜜的。在你当前的 PoSh 环境中导入函数后,你可以使用下面的命令来得到你想要的结果 -

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

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

# 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

【讨论】:

  • ..如果我不想删除重复的列。需要从上面的代码中更改什么
  • 如果您尝试使用Add-Memberb.csv 添加VM 列,我怀疑您是否可以通过上述代码实现此目的,它会抱怨成员VM 已经存在。你可以使用类似的东西 - gc $a = a.csv; gc $b = b.csv; 0..($b.Count – 1) | %{$a[$_],$b[$_] -join ','} | Out-File $outFile
猜你喜欢
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2018-10-31
  • 2013-01-11
  • 2013-07-14
  • 2018-08-29
  • 2019-04-29
相关资源
最近更新 更多