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

求PowerShell脚本:按首列合并文本文件重复行

PowerShell实现文本合并方案

给定输入文本:

A a
B b
C c
C d
C e
C f

期望输出:

A: a
B: b
C: c, d, e, f

可以用以下PowerShell脚本实现:

# 读取文件并处理后输出到新文件
Get-Content .\input.txt | ForEach-Object {
    $parts = $_.Trim() -split '\s+', 2
    [PSCustomObject]@{
        Key = $parts[0]
        Value = $parts[1]
    }
} | Group-Object Key | ForEach-Object {
    "$($_.Name): $($_.Group.Value -join ', ')"
} | Set-Content .\output.txt

脚本说明

  1. 解析文本行:Get-Content读取文件每行内容,Trim()去除首尾空白,-split '\s+',2按一个或多个空格分割成两部分(兼容值包含空格的场景),将每行封装为带Key和Value的自定义对象。
  2. 分组聚合:Group-Object Key按首字符分组,把相同键的条目归为一组。
  3. 格式化输出:对每个分组,用-join ', '拼接所有对应值,按键: 值格式输出,最后写入目标文件。

如果需要直接修改原文件(类似awk的-i inplace),可以用:

$processedContent = Get-Content .\input.txt | ForEach-Object {
    $parts = $_.Trim() -split '\s+', 2
    [PSCustomObject]@{
        Key = $parts[0]
        Value = $parts[1]
    }
} | Group-Object Key | ForEach-Object {
    "$($_.Name): $($_.Group.Value -join ', ')"
}
$processedContent | Set-Content .\input.txt

与原Bash脚本对比

原awk脚本通过维护变量和数组实现分组拼接,PowerShell则利用面向对象特性,通过分组对象更直观完成逻辑,代码可读性更强,也更贴合PowerShell的惯用写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:03:38