Powershell 脚本 - 使用正则表达式递归搜索文件中的字符串并将正则表达式组输出到文件
Powershell scripting - searching for string in files recursively using regex and outputting regex groups to file
我正在使用正则表达式递归搜索指定文件夹中的所有文件。这些是正在使用的图标 (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
我希望能够独立引用每个部分,所以说我可以 return 'fa-some-icon far' 而不是加上当我向这个脚本中添加更多内容时,能够引用它们会派上用场。
来自 Select-String
的 Microsoft.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
我正在使用正则表达式递归搜索指定文件夹中的所有文件。这些是正在使用的图标 (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
我希望能够独立引用每个部分,所以说我可以 return 'fa-some-icon far' 而不是加上当我向这个脚本中添加更多内容时,能够引用它们会派上用场。
来自 Select-String
的 Microsoft.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