我有一个完美的正则表达式,但我想添加在文件中,其中的正则表达式被发现,当前代码:
$results = Get-ChildItem ../MyDir -filter "*.txt" -Recurse | Get-Content |
Select-String -pattern "Token: ([^']*)" -AllMatches |
% {$_.Matches} | % {$_.Groups[1].Value}
需要:
$results = Get-ChildItem ../MyDir -filter "*.txt" -Recurse | Get-Content |
Select-String -pattern "Token: ([^']*)" -AllMatches |
% {$_.Matches} | % {<<FileNameMatchWasFoundIn>> + $_.Groups[1].Value}
不把它分解成一个大的for循环是可能的吗?
直接管道到Select-String
,结果输出对象将具有一个Path
属性,文件名为:
$results = Get-ChildItem ../MyDir -filter "*.txt" -Recurse | Select-String -pattern "Token: ([^']*)" -AllMatches |ForEach-Object {
New-Object psobject -Property @{
File = $_.Path
Matches = $_.Matches |% {$_.Groups[1].Value}
}
}
如果你只想要一个字符串作为结果:
$results = Get-ChildItem ../MyDir -filter "*.txt" -Recurse | Select-String -pattern "Token: ([^']*)" -AllMatches |ForEach-Object {
"{0}: {1}" -f $_.Path,$(($_.Matches|%{$_.Groups[1].Value}) -join ";")
}