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

如何使用PowerShell从Git提交记录中提取PR编号

问题

我有一个包含Git提交记录的文件,内容如下:

c2b7b1913 Merged PR 38064: Lorem ipsum dolor sit amet
baa810a57 Merged PR 37937: Lorem ipsum dolor sit amet
8d67d563c Merged PR 37825: Lorem ipsum dolor sit amet
2a061da0b Merged PR 37494: Lorem ipsum dolor sit amet

我希望用PowerShell仅提取其中的PR编号,得到如下结果:

38064
37937
37825
37494

我尝试了以下命令:

Get-Content .\testdata.txt `
| Select-String -Pattern "^.*Merged PR (\d{5}):.*$" -AllMatches `
| ForEach-Object {$_.Matches.Groups}

该命令返回了如下输出,但我不知道如何获取正则组中的内容:

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 54
Value    :  c2b7b1913 Merged PR 38064: Lorem ipsum dolor sit amet

Success  : True
Name     : 1
Captures : {1}
Index    : 21
Length   : 5
Value    : 38064

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 54
Value    :  baa810a57 Merged PR 37937: Lorem ipsum dolor sit amet

Success  : True
Name     : 1
Captures : {1}
Index    : 21
Length   : 5
Value    : 37937

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 54
Value    :  8d67d563c Merged PR 37825: Lorem ipsum dolor sit amet

Success  : True
Name     : 1
Captures : {1}
Index    : 21
Length   : 5
Value    : 37825

Groups   : {0, 1}
Success  : True
Name     : 0
Captures : {0}
Index    : 0
Length   : 54
Value    :  2a061da0b Merged PR 37494: Lorem ipsum dolor sit amet

Success  : True
Name     : 1
Captures : {1}
Index    : 21
Length   : 5
Value    : 37494

对应的sed命令如下:

sed -nE 's/^.*Merged PR ([[:digit:]]{5}):.*$/\1/p' 
解决方案

方法一:提取捕获组内容

你的正则已经正确匹配到了PR编号(第一个捕获组),只需在ForEach-Object中指定提取该组的Value属性即可:

Get-Content .\testdata.txt `
| Select-String -Pattern "^.*Merged PR (\d{5}):.*$" `
| ForEach-Object { $_.Matches.Groups[1].Value }
  • Groups[0]是整行的匹配结果,Groups[1]对应你用括号定义的捕获组,也就是PR编号
  • .Value用于获取该组的具体文本内容

方法二:用-replace简化操作

如果不需要严格的整行匹配校验,直接用字符串替换就能快速提取编号:

Get-Content .\testdata.txt | ForEach-Object { $_ -replace '^.*Merged PR (\d{5}):.*$', '$1' }

这里$1指代正则中的第一个捕获组,替换后直接输出编号。

方法三:更高效的匹配方式

可以简化正则表达式,只匹配关键部分,同时直接用Select-String指定文件路径,减少管道步骤:

Select-String -Path .\testdata.txt -Pattern "Merged PR (\d{5}):" | ForEach-Object { $_.Matches.Groups[1].Value }

只要行中存在Merged PR 五位数字:的结构,就能正确提取编号,结果和之前一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:57:26