我试图只从文本文件中提取我的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"但是,这将返回整行,也不会消除重复。我尝试了regex,但我对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发布于 2015-07-31 19:15:21
应该使用这样的方法:
$Jira_Num = Get-Content /tmp/jira.txt | ForEach-Object {
if ($_ -match '^([A-Z]+-[0-9]+)') {
$Matches[1]
}
} | Select-Object -UniqueGet-Content逐行读取文件,因此我们可以将其传输到其他cmdlet以处理每一行。
ForEach-Object为管道中的每个项目运行一个命令块。在这里,我们使用-match操作符对行执行regex匹配,并使用捕获组。如果匹配成功,则将匹配的组( JIRA问题密钥)发送到管道中。
Select-Object -Unique将比较这些对象,并只返回唯一的对象。
发布于 2015-07-31 19:37:15
Select-String仍然可以工作!这个问题来自于对返回对象的误解。它返回一个[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是故意的。
https://stackoverflow.com/questions/31753492
复制相似问题