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

如何在PowerShell中合并同标识字符串对应的数值并输出结果?

完善后的PowerShell字符分组求和脚本

完整实现代码

# 替换为你的目标文件路径
$inputFilePath = "your_input_file.txt"
# 读取文件并过滤空行
$content = Get-Content $inputFilePath | Where-Object { $_ -match '\S' }

# 初始化哈希表存储分组求和结果
$sumDictionary = @{}

foreach ($line in $content) {
    # 拆分每行内容(支持多空格/制表符分隔,可按需调整分隔规则)
    $columns = $line -split '\s+'
    $targetChar = $columns[0]
    $numericValue = [int]$columns[1]

    # 累加对应字符的数值
    if ($sumDictionary.ContainsKey($targetChar)) {
        $sumDictionary[$targetChar] += $numericValue
    } else {
        $sumDictionary[$targetChar] = $numericValue
    }
}

# 按字符排序并输出指定格式结果
$sumDictionary.GetEnumerator() | Sort-Object Key | ForEach-Object {
    Write-Output "$($_.Key): $($_.Value)"
}

可自定义调整项

  • 分隔符适配:如果输入列用逗号/制表符分隔,将-split '\s+'替换为对应规则,比如制表符用-split "t",逗号用-split ','`
  • 数值类型兼容:若输入为浮点数,把[int]改为[double]或[decimal]
  • 输出到文件:将最后一步的Write-Output改为管道输出到文件,示例:
    $sumDictionary.GetEnumerator() | Sort-Object Key | ForEach-Object { "$($_.Key): $($_.Value)" } | Out-File "output_result.txt"
    

测试示例

假设输入文件内容:

A 12
B 8
A 8
C 5
B 12

执行脚本后输出:

A: 20
B: 20
C: 5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:25:40