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.

Clijsters
  • 4,031
  • 1
  • 27
  • 37
Medazou
  • 21
  • 4

2 Answers2

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
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

Medazou
  • 21
  • 4