使用 PowerShell 搜索正则表达式模式并输出文件名

Search regex pattern with PowerShell and output filename

$input_path = "d:\txt\*.txt"
$output_file = 'd:\out.txt'
$regex = "\w* (\w\.? )?\w* (was )?[B|b]orn .{100}"
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

这里是 Powershell 初学者。我希望它遍历特定​​目录中的所有文件,搜索特定的正则表达式模式并将结果输出到文件。到目前为止,我已经设法解决了上述问题。我怎样才能让它也输出每个匹配项的文件名?

最后一行使用:

# put matches into var
$matches = Select-String -Path $input_path -Pattern $regex -AllMatches
# write out to file
foreach ($m in $matches) { $m.Filename | Out-File $output_file -Append -NoClobber }

您可以执行以下操作:

$input_path = "d:\txt\*.txt"
$output_file = 'd:\out.txt'
$regex = "\w* (\w\.? )?\w* (was )?[B|b]orn .{100}"
Select-String -Path $input_path -Pattern $regex -AllMatches | Foreach-Object {
    $currentMatches = $_
    $_.Matches | Foreach-Object { $_.Value,$currentMatches.Filename -join ' | ' } |
        Add-Content $output_file
}

解释:

Select-String 将 return MatchInfo 个对象的集合。这些对象中的每一个都有一个 Filename 属性,其中仅包含包含匹配项的文件的文件名。由于单个文件中可能有多个匹配项(由于 -AllMatches),因此有必要遍历 MatchInfo 对象中的每个匹配项。

-join 运算符使用定义的字符串分隔符连接集合中的所有项目。