How to replace only a portion of string using PowerShell Get-Content -replace

1.9k Views Asked by At

I have a file in which I need to modify a URL, not knowing what that URL contains, just like in the following example: In file file.txt I have to replace the URL, so that wether it is "https://SomeDomain/Release/SomeText" or "https://SomeDomain/Staging/SomeText" to "https://SomeDomain/Deploy/SomeText". So like, whatever is written between SomeDomain and SomeText, it should be replaced with a known String. Are there any regex that can help me achieve this?

I used to do it with the following command"

((Get-Content -path "file.txt" -Raw) -replace '"https://SomeDomain/Release/SomeText");','"https://SomeDomain/Staging/SomeText");') | Set-Content -Path "file.txt"

This works fine, but I have to know if in file.txt the URL contains Release or Staging before executing the command.

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

You can do this with a regex -replace, where you capture the parts you wish to keep and use the backreferences to recreate the new string

$fileName = 'Path\To\The\File.txt'
$newText  = 'BLAHBLAH'

# read the file as single multilined string
(Get-Content -Path $fileName -Raw) -replace '(https?://\w+/)[^/]+(/.*)', "`$1$newText`$2" | Set-Content -Path $fileName

Regex details:

(              Match the regular expression below and capture its match into backreference number 1
   http        Match the characters “http” literally
   s           Match the character “s” literally
      ?        Between zero and one times, as many times as possible, giving back as needed (greedy)
   ://         Match the characters “://” literally
   \w          Match a single character that is a “word character” (letters, digits, etc.)
      +        Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   /           Match the character “/” literally
)             
[^/]           Match any character that is NOT a “/”
   +           Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(              Match the regular expression below and capture its match into backreference number 2
   /           Match the character “/” literally
   .           Match any single character that is not a line break character
      *        Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)