使用powershell在csv中合并两行或多行 [英] Combine two or more rows in a csv using powershell

查看:52
本文介绍了使用powershell在csv中合并两行或多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我们的一个客户那里收到一个文件,看起来像这样:(为了更容易处理,我为此添加了标题).样本输入:

I receive a file from one of our clients that looks like this: (I added headers to this to it for easier processing). Sample Input:

PlanID,Date,Transaction,Type,Ticker,Amount,Cash
01,121211,div,mf,fjk,25,cash
01,121211,div,mf,fjk,30,cash
01.121211,buy,mf,fjk,55,cash
02,121211,div,sd,ejd,10,cash
02,121211,div,sd,ejd,15,cash
02,121211,buy,sd,ejd,25,cash

我需要一种方法,通过对每个 PlanID 的金额求和来组合所有带有 Transaction='div' 的行.这就是我希望我的输出的样子:

I need a way to combine all the rows with Transaction= 'div' by summing up their amount for each PlanID. This is how I desire my output to look like:

样本输出:

PlanID,Date,Transaction,Type,Ticker,Amount,Cash
01,121211,div,mf,fjk,55,cash
01.121211,buy,mf,fjk,55,cash
02,121211,div,sd,ejd,25,cash
02,121211,buy,sd,ejd,25,cash

因此,在购买行之前只有一个 div 行(金额相加,将始终是购买金额).任何想法如何解决这个问题将不胜感激?

So, there is only one div row before buy row (with amount summed up, will always be the buy amount). Any ideas how to approach this would be greatly appreciated?

非常感谢!

推荐答案

Import-Csv input.csv | Group-Object planid, transaction | 
Select @{n="PlanId";E={($_.name -split ',')[0]}},
       @{n="Date";e={($_.group)[0].date}}, 
       @{n="Transaction";E={(($_.name -split ',')[1]).trim()}},
       @{n="Type";e={($_.group)[0].type}},  
       @{n="Ticker";e={($_.group)[0].ticker}}, 
       @{n="Amount";e={($_.group | measure-object amount -sum).sum}},
       @{n="Cash";e={($_.group)[0].cash}} |
Export-Csv output.csv -NoTypeInformation

步骤:

  1. 导入 input.csv 文件
  2. 按计划和事务对对象进行分组
  3. 在输出中选择所需的属性
  1. Import the input.csv file
  2. Group the objects by planid and transaction
  3. Select the properties you want in your output
  1. PlanId = group-object 返回的对象的名称字段中逗号的剩余部分
  2. Transaction = group-object 返回的对象的名称字段中逗号右侧的任何内容
  3. 金额 = 每个分组对象的所有金额的总和
  4. 日期 = 每个分组对象的日期
  5. 类型 = 每个分组对象的类型
  6. Ticker = 每个分组对象的代码
  7. 现金 = 每个分组对象的现金

  • 将对象导出到 output.csv(添加 notypeinformation 以去除带有类型信息的顶行)
  • 这篇关于使用powershell在csv中合并两行或多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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