2

I am looking for a string of specific characters in a text file; I use

Select-String -Path clm-server-test.txt -Pattern "#(S****)"

I want to get only that characters matching the pattern, but it returns also characters before and after that string.

For example :

I have a registration set that starts with

S32145 thomas
S12345 bedro
S09867 stephane

with the Select-String command I want it to show me all the S *** words, not the names.

1
  • 3
    Just search for the string you want: (S\d+) Commented Sep 5, 2018 at 16:31

2 Answers 2

3
  • Select-String's -Pattern parameter by default expects a regex (regular expression) to search for.

    • "#(S****)" is not a valid regex (it looks more like a wildcard expression, except that you'd use ? to match a single character).

    • To match just the tokens that start with S followed by 5 digits, use S\d{5}, or, to match any number of digits, use S\d+, as TheIncorrigible1 suggests.
      Also, you could refine the regex to match only at word boundaries (\b): '\bS\d{5}\b'

  • Select-String doesn't support outputting just the matching parts of lines, but you can do that by further processing the [Microsoft.PowerShell.Commands.MatchInfo] instances that it outputs.

To put it all together:

Select-String -Path clm-server-test.txt -Pattern '\bS\d{5}\b' | 
  ForEach-Object { $_.Matches[0].Value }

With your sample input this yields:

S32145
S12345
S09867 

As an aside: As evident from the command above, Select-String currently doesn't make it easy to extract just the matching parts of the input lines.
If you're interested in having a switch introduced that simplifies this, participate in the discussion on GitHub.

Sign up to request clarification or add additional context in comments.

Comments

0

thank you for your answer and for yours in fact, your order to bring me closer to the expected result except that, I would like him to return to me that the word that begins with a "S ***" until now point on the line in all things that I would like to avoid.

I would like him to see me the number "S7676583"

Thank you so much

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.