【问题标题】:PowerShell - Read data from a csv file, compare data from a specific column and write the results to a new filePowerShell - 从 csv 文件读取数据,比较特定列中的数据并将结果写入新文件
【发布时间】:2022-01-18 02:17:46
【问题描述】:

我是 PowerShell 新手,想征求您的意见。我有一个“传入”csv 文件,我需要通过执行以下操作来创建一个“传出”csv 文件。

  1. 将“传入”文件的内容原样复制到“传出”文件中。
  2. 遍历“ID”列并为每个唯一 ID,复制该行并附加“传出”文件。

传入文件示例:

传出文件样本:

这可以通过 PowerShell 实现吗?

【问题讨论】:

  • 真实的ID 值是否应该是唯一的?两个文件示例中都有重复项。蓝色文本表示您只希望复制每个 ID 的第一个实例?
  • 不,“ID”值可以重复。您是对的 - 只需复制每个 ID 的第一个实例。

标签: powershell csv comparison


【解决方案1】:

这就是你所描述的:

# Import your data
$incoming = Import-Csv 'c:\folder\incoming.csv'

# 1. Copy Incoming onto Outgoing:
$incoming | Select *,NewColumn | Export-Csv C:\temp\test.csv -Append -NoTypeInformation

# 2. Append the first Incoming row with a unique ID to Outgoing:
$incoming | 
  Group-Object ID |        ## Group rows by ID
  Foreach {$_.Group[0]} |  ## Select first row per ID
  Select *,@{l='NewColumn';e={"Added via script"}} |  ## Add column
  Export-Csv 'c:\folder\outgoing.csv' -Append -NoTypeInformation

# example incoming:
ID  Invoice Paid
--  ------- ----
100 100     150 
100 50      150 
101 200     200 
102 500     850 
102 250     850 
102 100     850 

# creates this outgoing (assuming EMPTY outgoing file to start with):
ID  Invoice Paid NewColumn       
--  ------- ---- ---------       
100 100     150                  
100 50      150                  
101 200     200                  
102 500     850                  
102 250     850                  
102 100     850                  
100 100     150  Added via script
101 200     200  Added via script
102 500     850  Added via script

请注意,Outgoing csv 文件必须已经添加了 NewColumn 字段,以便 -Append 在使用现有文件时正常工作。否则您的新列将不会被导出。

【讨论】:

  • 效果很好!非常感谢。还有一个问题 - 是否可以在新添加的行中添加静态文本(如“通过脚本添加”)以指示原始文件没有它们。
  • @John 它将不再是有效的 csv 文件,但您始终可以在步骤之间添加 "Added via script" | Out-File 'c:\folder\outgoing.csv' -Append。或者你的意思是像一个额外的列?
  • 是的,我的意思是增加一列。
  • @John 我已经编辑了我的答案。
猜你喜欢
  • 2022-12-24
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多