合并两个CSV文件,同时添加新文件并覆盖现有条目 [英] Merge two CSV files while adding new and overwriting existing entries

查看:135
本文介绍了合并两个CSV文件,同时添加新文件并覆盖现有条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个configuration.csv,它保存这样的模板数据:

I have a configuration.csv that holds a template data like this:

| path       | item  | value  | type |
|------------|-------|--------|------|
| some/path  | item1 | value1 | ALL  |
| some/path  | item2 | UPDATE | ALL  |
| other/path | item1 | value2 | SOME |

customization.csv具有服务特定的配置:

and customization.csv that has service specific configuration:

| path       | item  | value  | type |
|------------|-------|--------|------|
| some/path  | item2 | value3 | ALL  |
| new/path   | item3 | value3 | SOME |

我的目标是将它们合并,最终得到这样的结果:

My goal is to merge them and end up with something like this:

| path       | item  | value  | type |
|------------|-------|--------|------|
| some/path  | item1 | value1 | ALL  |
| some/path  | item2 | value3 | ALL  |
| other/path | item1 | value2 | SOME |
| new/path   | item3 | value3 | SOME |

这应该添加任何新条目,并更新任何现有条目.没有任何一栏可用于唯一标识-pathitem都需要结合使用,因为它们保证是唯一的.

This should add any new entries and update any existing ones. No one column can be used for unique identification - both path and item needs to be combined, as they are guaranteed to be unique.

推荐答案

我建议使用Compare-Object,因为customization.csv中的值将持久存在,请使用此文件中的-ReferenceObject

I suggest to use Compare-Object and as the values from customization.csv shall persist use this files values as -ReferenceObject

## Q:\Test\2019\03\01\SO_54948111.ps1

$conf = Import-Csv '.\configuration.csv'
$cust = Import-Csv '.\customization.csv'

$NewData = Compare-Object -ref $cust -diff $conf -Property path,item -PassThru -IncludeEqual|
    Select-Object -Property * -ExcludeProperty SideIndicator

$NewData
$NewData |Export-Csv '.\NewData.csv' -NoTypeInformation

样本输出

> Q:\Test\2019\03\01\SO_54948111.ps1

path       item  value  type
----       ----  -----  ----
some/path  item2 value3 ALL
some/path  item1 value1 ALL
other/path item1 value2 SOME
new/path   item3 value3 SOME

这篇关于合并两个CSV文件,同时添加新文件并覆盖现有条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆