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

PowerShell比较CSV字符串时圆括号匹配失败问题求助

PowerShell匹配含圆括号的CSV字符串失败问题解决

问题场景

需要对比两个CSV文件的Testdefinition列:若CSV2中的字符串存在于CSV1对应列中,给CSV1对应行添加TestLabel标签。目前普通字符串匹配正常,但含圆括号的字符串无法匹配,无报错也无匹配结果。

CSV1内容

Testdefinition;Stichwörter;Stichwörter;Stichwörter;Stichwörter;Stichwörter
It is just a normal text (with round brackets).Test: success;ExistingLabel;;;;
This is a second text;;;
Another text;ExistingLabel;;;;
One more text for the testing - success;ExistingLabel;;;;

CSV2内容

Testdefinition;Stichwörter;Stichwörter;Stichwörter;Stichwörter;Stichwörter
It is just a normal text (with round brackets).Test: success
One more text for the testing - success

原脚本问题点

原脚本使用Select-String $testSearch时,默认将搜索字符串当作正则表达式解析,而圆括号()是正则的分组元字符,会被特殊处理,导致无法匹配原字符串中的字面量括号。

解决思路与优化方案

  1. 强制字面量匹配:给Select-String添加-SimpleMatch参数,禁用正则解析,直接匹配原始字符串
  2. 简化匹配逻辑:用PowerShell的-in运算符直接检查字符串是否存在于CSV2的Testdefinition数组中,更高效简洁
  3. 移除冗余临时文件:Import-Csv可以通过Get-Content | Select-Object -Skip 1 | ConvertFrom-Csv直接读取跳过表头的内容,无需生成临时文件

修改后的完整脚本

$header = 'Testdefinition', 'Stichwörter1', 'Stichwörter2', 'Stichwörter3', 'Stichwörter4', 'Stichwörter5'
$exportheader = "Testdefinition;Stichwörter;Stichwörter;Stichwörter;Stichwörter;Stichwörter"

$path1 = 'D:\data\.....test.csv'
$path2 = 'D:\data\.....test_failed.csv'
$exportfile = 'test.csv'

# 直接读取并跳过表头,无需临时文件
$file1 = Get-Content $path1 -Encoding UTF8 | Select-Object -Skip 1 | ConvertFrom-Csv -Delimiter ";" -Header $header
$file2 = Get-Content $path2 -Encoding UTF8 | Select-Object -Skip 1 | ConvertFrom-Csv -Delimiter ";" -Header $header

# 提取CSV2的Testdefinition列作为匹配集合
$failedTests = $file2.Testdefinition

Write-Output "`nSearching for failed results"

# 写入表头
Set-Content $exportfile -Value $exportheader -Encoding UTF8

foreach ($row in $file1) {
    $testDef = $row.Testdefinition
    Write-Output "The Testdefinition is: $testDef"

    # 检查当前字符串是否存在于CSV2的集合中
    if ($testDef -in $failedTests) {
        # 找到匹配,添加TestLabel
        $matchIndex = [array]::IndexOf($failedTests, $testDef) + 1 # 行号从1开始
        Write-Output "Testline found: $testDef in Line $matchIndex"
        $exportLine = "$testDef;$matchIndex;TestLabel"
    }
    else {
        # 未找到匹配
        Write-Output "Testline not found"
        $exportLine = "$testDef;;NULL"
    }

    Write-Output $exportLine
    Add-Content $exportfile -Value $exportLine -Encoding UTF8
    Write-Output ""
}

# 验证导出结果
$exportCsv = Import-Csv $exportfile -Delimiter ";" -Header $header
$exportCsv | Format-Table

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:45:31