You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对比含Ticket列的两个CSV,生成匹配Alert_ID的新CSV?

问题描述

现有两个CSV文件,其中csv2包含额外的Ticket(工单编号)列。需要以csv1的内容为基准,对比两个文件的Alert_ID,将csv2中匹配项的Ticket值填充到对应行,无匹配项则Ticket列留空。

数据示例

csv1内容

Alert_ID,Server,Type,Timestamp,Severity
1234,Srv1,WIN,2023-03-10,Critical
1235,Srv1,Net,2023-03-9,Critical
1236,Srv2,WIN,2023-03-8,Critical
1237,Srv3,WIN,2023-03-10,Critical

csv2内容

Alert_ID,Server,Type,Timestamp,Severity,Ticket
1234,Srv1,WIN,2023-03-10,Critical,INC1
1236,Srv2,WIN,2023-03-8,Critical,INC3
1238,Srv4,NET,2023-02-10,Critical,INC01
1239,Srv5,NET,2023-02-20,Critical,INC02

预期输出(csv3)

Alert_ID,Server,Type,Timestamp,Severity,Ticket
1234,Srv1,WIN,2023-03-10,Critical,INC1
1235,Srv1,Net,2023-03-9,Critical,
1236,Srv2,WIN,2023-03-8,Critical,INC3
1237,Srv3,WIN,2023-03-10,Critical,

尝试的错误代码

$csv1 = Import-Csv .\csv1.csv
$csv2 = Import-Csv .\csv2.csv
#csv2 | where-object { $csv1.Alert_ID -match $_.Alert_ID} | export-csv .\csv3.csv -notype
解决方案

核心思路是先把csv2中的Alert_ID和对应Ticket存入哈希表,实现快速查找;再遍历csv1的每一行,添加Ticket属性并完成赋值,最后导出为新CSV文件。

# 导入两个CSV文件
$csv1 = Import-Csv .\csv1.csv
$csv2 = Import-Csv .\csv2.csv

# 构建Alert_ID到Ticket的哈希表,提升匹配效率
$ticketMap = @{}
foreach ($item in $csv2) {
    $ticketMap[$item.Alert_ID] = $item.Ticket
}

# 遍历csv1,为每一行添加Ticket属性
$csv3 = $csv1 | ForEach-Object {
    [PSCustomObject]@{
        Alert_ID  = $_.Alert_ID
        Server    = $_.Server
        Type      = $_.Type
        Timestamp = $_.Timestamp
        Severity  = $_.Severity
        Ticket    = if ($ticketMap.ContainsKey($_.Alert_ID)) { $ticketMap[$_.Alert_ID] } else { '' }
    }
}

# 导出到csv3.csv,排除类型注释并指定UTF8编码
$csv3 | Export-Csv .\csv3.csv -NoTypeInformation -Encoding UTF8

代码说明

  1. 哈希表构建:遍历csv2将Alert_ID作为键、Ticket作为值存入哈希表,后续匹配时查找速度远快于逐行对比。
  2. 自定义对象生成:保留csv1原有所有属性,新增Ticket属性,通过哈希表判断是否存在匹配项,存在则赋值对应Ticket,否则设为空字符串。
  3. 导出设置:-NoTypeInformation避免CSV开头生成无用的类型注释,-Encoding UTF8保证文件编码兼容性。

内容的提问来源于stack exchange,提问作者Enigma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 19:18:16