PowerShell for Windows Admins

Jan 10 2014   6:28AM GMT

Finding a sequence



Posted by: Richard Siddaway
Tags:
PowerShell Basics

I saw a challenge to find the occurrences of the sequence 1759 in the larger sequence 11759171759.  It was originally presented as a SQL Server based challenge to be solved with TSQL but we can do this just as easily with PowerShell using Select-String

£> $data = ’11759171759′
£> Select-String -InputObject $data -Pattern ’1759′ -AllMatches | foreach {$_.Matches.Index}

1
7

Create a variable to hold the big sequence and use that with the –InputObject parameter of Select-String. Supply the pattern to be tested and use –AllMatches to get all matches not just the first which is default. The resultant MatchInfo is piped to foreach-object where the Index of each match is retrieved.

if you want to see the full MatchInfo

£> $m = Select-String -InputObject $data -Pattern ’1759′ -AllMatches
£> $m.Matches
Groups   : {1759}
Success  : True
Captures : {1759}
Index    : 1
Length   : 4
Value    : 1759

Groups   : {1759}
Success  : True
Captures : {1759}
Index    : 7
Length   : 4
Value    : 1759

The indexes are zero based.  Add one if you want the position based on a starting index of 1

£> foreach ($match in (Select-String -InputObject $data -Pattern ’1759′ -AllMatches).Matches){$match.Index + 1}
2
8

Interesting puzzle that gives a good example of using Select-String

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: