powershell - 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”,而且当我向这个脚本添加更多内容时,能够引用它们会派上用场。
解决方案
对象的Value
属性将包含包含匹配项的整行。要仅访问匹配项或匹配项的各个组,请分别使用属性及其属性。Microsoft.PowerShell.Commands.MatchInfo
Select-String
Groups
Value
更改此行:
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
推荐阅读
- python - 向 pandas 列中的字符串添加零取决于长度
- angular - Angular + Service Worker:如何将 `apiUrl` 从`environment.ts` 传递给`sw-sync.js`?
- javascript - 如何从 CSV json 对象中删除一个值?
- java - 使用 web.xml 在 Tomcat 8 上设置自定义过滤器
- python-3.x - 将输入文件修改为所需的输出文件
- javascript - 使用 jquery 倒计时
- vue.js - 我可以访问本地系统环境吗?使用 vue-cli 时的变量?
- ocaml - 如何读取文件并将其写入不同的文件
- javascript - 基础 javascript 没有按预期工作
- shell - 如何在床文件中对具有相同名称的序列进行编号