user756659
user756659

Reputation: 3510

Powershell scripting - searching for string in files recursively using regex and outputting regex groups to file

I am recursively searching all files in a specified folder using regex. These are icons (fontawesome) that are being used and I want to create a list of each that I use in my project. They are in the format fa(l, r, s, d, or b) fa-(a-z and -). My script below is working and outputs each it finds in a new line. If you noticed I grouped the first and second part of the regex though... how can I reference and ouput those groups rather than the whole match as it is currently?

$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

An example results.txt would be something like :

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

I want to be able to reference each part independently so say I could return 'fa-some-icon far' instead plus as I add more to this script it will come in handy being able to reference them.

Upvotes: 0

Views: 2408

Answers (1)

stackprotector
stackprotector

Reputation: 13567

The Value property of a Microsoft.PowerShell.Commands.MatchInfo object from Select-String will contain the whole line that contains the match. To access just the match or individual groups of the match, use the Groups property and its Value property respectively.

Change this line:

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

To the following line to get your desired output:

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

Or to the following line to get the output with both matching groups reversed:

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

Upvotes: 2

Related Questions