【问题标题】:Powershell scripting - searching for string in files recursively using regex and outputting regex groups to filePowershell脚本 - 使用正则表达式递归搜索文件中的字符串并将正则表达式组输出到文件
【发布时间】:2020-06-10 06:18:56
【问题描述】:

我正在使用正则表达式递归搜索指定文件夹中的所有文件。这些是正在使用的图标(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”,而且当我向这个脚本添加更多内容时,能够引用它们会派上用场。

【问题讨论】:

    标签: powershell select-string


    【解决方案1】:

    来自Select-StringMicrosoft.PowerShell.Commands.MatchInfo 对象的Value 属性将包含包含匹配项的整行。要仅访问比赛或比赛的各个组,请分别使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      相关资源
      最近更新 更多