-2

How can we replace multiple match with only one word/phrase replace using powershell

Below are the matches in the regex

Grant access to Server1
Grant access to Server2
Grant access to Server3
Grant access to Server4

Need to replace all the results above with only one phrase below,

Word of the day!

Ian
  • 9
  • 4

1 Answers1

0

I am not entirely sure what the OP is going for but you are looking to just match all lines with the following

Grant access to Server1
Grant access to Server2
Grant access to Server3
Grant access to Server4

You can use this as your pattern (Grant access to Server\d+(\n)?){4}. This will match the raw text "Grant access to Server" followed by at least one digit. In the event the last item is at the end of the string (last item wont have a newline) we include the optional (\n)? for newline. At the end the quatifier of {4} since the example only had 4 occurances. you could easily replace {4} with * as a greedy capture of all occurances in sequence.

So (Grant access to Server\d+(\n)?)* would also match:

Grant access to Server1
Grant access to Server3
Grant access to Server44325
Grant access to Server4
Grant access to Server44
Grant access to Server3
Matt
  • 45,022
  • 8
  • 78
  • 119