Regex Return Only First Match

by JonathanGrocott at 2013-02-28 21:55:28

I am new to the site and new to Power-shell -->Really excited about digging deeper.

I am trying to write a Run-time value from a post .lst file with a SEQ# identifier. Here is what i have:

# Returns the Total Run Time from .lst files in directory $inputpath #
$input_path = ‘C:\RUN_TIME_TEST*.lst’
$output_file = ‘C:\RUN_TIME_TEST\Test.csv’
$items = ‘TOTAL…\d\d:\d\d:\d\d’
$items2 = ‘SEQ_\d*’
$regex = $items
$regex2 = $items2

select-string -Path $input_path -Pattern $regex2 -AllMatches | % { $.Matches } | % { $.Value } > $output_file
select-string -Path $input_path -Pattern $regex -AllMatches | % { $.Matches } | % { $.Value } >> $output_file

The regex2 returns 3 Seq values (-allmatches) and i only want one value returned. Appreciate any and all help.
by AlexBrassington at 2013-02-28 23:06:47
If you just want the first result you need to remove the -AllMatches switch.
by JonathanGrocott at 2013-02-28 23:36:00
I should have left that out. Even without the -AllMatches switch it outputs all 3 occurrences of SEQ_##.
by AlexBrassington at 2013-03-01 00:15:25
Good point. When you use the -Path parameter it returns all matches by default.

Try this:

select-string -Path $input_path -Pattern $regex2 -AllMatches | Select -First 1 > $output_file
by mjolinor at 2013-03-01 03:13:28
-List <SwitchParameter>
Returns only the first match in each input file. By default, Select-String returns a MatchInfo object for each match it finds.

select-string -Path $input_path -Pattern $regex2 -List
by JonathanGrocott at 2013-03-02 04:35:44
Thanks guys. This worked great:
select-string -Path $input_path -Pattern $regex2 -List | % { $.Matches } | % { $.Value } > $output_file