Powershell 查找特定模式

Powershell to find specific pattern

我正在尝试从文本文件中仅提取我的 JIRA 问题编号,以消除重复项。这在 Shell 脚本中很好:

 cat /tmp/jira.txt | grep -oE '^[A-Z]+-[0-9]+' | sort -u

但我想使用 Powershell 并尝试了这个

$Jira_Num=Get-Content /tmp/jira.txt |  Select-String -Pattern '^[A-Z]+-[0-9]+' > "$outputDir\numbers.txt"

但是,这returns整行也没有去重。我试过正则表达式,但我是 powershell 的新手,不知道如何使用它。有人可以帮忙吗?

样本Jira.txt文件

 PRJ-2303 Modified the artifactName
 PRJ-2303 Modified comment
 JIRA-1034 changed url to tag the prj projects
 JIRA-1000 for release 1.1
 JIRA-1000 Content modification

预期输出

 PRJ-2303
 JIRA-1034
 JIRA-1000

应该使用这样的东西:

$Jira_Num = Get-Content /tmp/jira.txt | ForEach-Object { 
    if ($_ -match '^([A-Z]+-[0-9]+)') {
        $Matches[1]
    }
} | Select-Object -Unique

Get-Content 逐行读取文件,因此我们可以将其通过管道传递给其他 cmdlet 以处理每一行。

ForEach-Object 为管道中的每个项目运行一个命令块。因此,我们在这里使用 -match 运算符对带有捕获组的行执行正则表达式匹配。如果匹配成功,我们将匹配的组(JIRA 问题密钥)发送到管道。

Select-Object -Unique 将比较对象,return 仅比较唯一的对象。

Select-String还能用!问题来自于对returnobject的误解。它 return 是一个 [Microsoft.PowerShell.Commands.MatchInfo] 并且 ToString() 等效项似乎是整个匹配行。我不知道您使用的是什么版本的 PowerShell,但这应该可以解决问题。

$Jira_Num = Get-Content /tmp/jira.txt | 
    Select-String  -Pattern '^[A-Z]+-[0-9]+' | 
    Select-Object -ExpandProperty Matches | 
    Select-Object -ExpandProperty Value -Unique

同时写入输出流和变量时,您也可能会得到奇怪的结果。通常在这种情况下使用 Tee-Object 会更好。

Select-String /tmp/jira.txt -Pattern '^[A-Z]+-[0-9]+' | 
    Select-Object -ExpandProperty Matches | 
    Select-Object -ExpandProperty Value -Unique | 
    Tee-Object -Variable Jira_Num | 
    Set-Content "$outputDir\numbers.txt"

现在文件 $outputDir\numbers.txt 和变量 $Jira_Num 包含唯一列表。未与 Tee-Object 一起使用的 $ 是故意的。