首页 > 解决方案 > Powershell脚本 - 使用正则表达式递归搜索文件中的字符串并将正则表达式组输出到文件

问题描述

我正在使用正则表达式递归搜索指定文件夹中的所有文件。这些是正在使用的图标(fontawesome),我想为我在项目中使用的每个图标创建一个列表。它们的格式为fa(l, r, s, d, or b) fa-(a-z and -). 我下面的脚本正在运行,并在新行中输出它找到的每一个。如果您注意到我将正则表达式的第一部分和第二部分分组......我如何引用和输出这些组而不是当前的整个匹配?

$input_path = 'C:\Users\Support\Downloads\test\test\'
$output_file = 'results.txt'
$regex = '(fa[lrsdb]{1}) (fa-[a-z-]+)'
Get-ChildItem $input_path -recurse | select-string -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

一个示例 results.txt 将类似于:

far fa-some-icon
fal fa-some-icon2
far fa-something-else
fas fa-another-one

我希望能够独立引用每个部分,所以说我可以返回“fa-some-icon far”,而且当我向这个脚本添加更多内容时,能够引用它们会派上用场。

标签: powershellselect-string

解决方案


对象的Value属性将包含包含匹配项的整行。要仅访问匹配项或匹配项的各个组,请分别使用属性及其属性。Microsoft.PowerShell.Commands.MatchInfoSelect-StringGroupsValue

更改此行:

Get-ChildItem $input_path -Recurse | Select-String -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

到以下行以获得所需的输出:

Get-ChildItem $input_path -Recurse | Select-String -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Groups[0].Value } > $output_file

或到以下行以获得两个匹配组反转的输出:

Get-ChildItem $input_path -Recurse | Select-String -Pattern $regex -AllMatches | % { $_.Matches } | % {"$($_.Groups[2].Value) $($_.Groups[1].Value)"} > $output_file

推荐阅读