arrays - Powershell CSV 导入。如果用户名匹配,则将值相加
问题描述
我有以下已导入 Powershell 数组的 CSV 文件
User Today MTD
---- ----- ---
User1 5 15
User1 3 32
User2 2 5
User1 1 23
User2 3 34
User3 3 34
如果用户匹配,我想将 Today 和 MTD 数字添加到一行
示例:用户 1 将是“今天”5+3+1=9“MTD”15+32+23=70
所需输出:
User Today MTD
---- ----- ---
User1 9 70
User2 5 39
User3 3 34
我可以使用列出一个用户名的数据
$arr.Where({$_.User -eq "user1"})
但不知道如何将今天和 MTD 加在一起
解决方案
There you go, I answered a very similar question here.
Code:
$csv = @'
User,Today,MTD
User1,5,15
User1,3,32
User2,2,5
User1,1,23
User2,3,34
User3,3,34
'@ | ConvertFrom-Csv
$csv | Group-Object User | ForEach-Object {
$_.Group[0].Today = ($_.Group.Today | Measure-Object -Sum).Sum
$_.Group[0].MTD = ($_.Group.MTD | Measure-Object -Sum).Sum
$_.Group[0]
}
Output:
User Today MTD
---- ----- ---
User1 9 70
User2 5 39
User3 3 34
Edit
To export the results you can do this:
$csv | Group-Object User | ForEach-Object {
# Original code here...
} | Export-Csv newCsv.csv -NoTypeInformation
Or this if you want to preserve the new object in memory:
$newCsv = $csv | Group-Object User | ForEach-Object {
# Original code here...
}
$newCsv | Export-Csv newCsv.csv -NoTypeInformation
推荐阅读
- java - Micrometer TimedAspect 不会拦截对使用 @Timed 注释的方法的调用
- r - ggplot:按工作日排序
- android - 无法使用 glide 库从 firebase 存储中获取图像
- velocity - 在衡量分析中的速度时如何考虑 UserStory 的故事点?
- nestjs - Nestjs自定义配置服务错误注入其他模块服务
- azure - Azure 全局管理员无法(禁用)在“访问控制(IAM)”下添加角色
- css - 反应改变风格取决于文本
- python - 用户输入的数据如何在 Django 的数据库中更新?
- flutter - 使用 Flutter 将文件上传到服务器时出错
- php - 修剪功能正在删除我在不同字符串中的最后一个字符