Forum Discussion

nancyvargas's avatar
nancyvargas
Copper Contributor
Dec 21, 2022

Powershell - string replacement using regex

Hi All,
I need help in powershell string replacement using regex.

I need to replace a decimal value after a specific string pattern with a new decimal value stored in a variable. Like, in the entire string, I need to replace all occurrences of ‘Version=xxx’ to ‘Version=$NewValue’. I tried the following but it didn’t work.

$New = $Orig.Replace(‘Version=(\d{1,3})’, ‘Version=$NewValue’)

$New = $Orig.Replace(‘Version=(\d*)’, ‘Version=$NewValue’)

Anyone has any suggestions?

Thanks
Nancy

  • jarleosmund's avatar
    jarleosmund
    Copper Contributor

    nancyvargas 

    $string = "This is a string with multiple Version=xxx values that need to be replaced." 
    $newValue = "3.14"
    # Replace all occurrences of "Version=xxx" with the new value
    $string -replace "Version=xxx", "Version=$newValue"

     

    Got it from OpenAI's chatGBT 🙂

  • Hi nancyvargas,

     

    You can use one of the following methods

    1. First, define the variables for the old value ("xxx") and the new value:
      $OldValue = "xxx"
      $NewValue = "your new value here"

      Next, use the Replace() method to find and replace all occurrences of the old value with the new value in a string:
      $string = "some string with Version=xxx and other text"
      $string = $string.Replace($OldValue, $NewValue)

    2. You can also use the -replace operator to do the same thing:
      $string = "some string with Version=xxx and other text"
      $string = $string -replace $OldValue, $NewValue

    3. If you want to replace all occurrences of "Version=xxx" in a file, you can use the Get-Content cmdlet to read the file into a string, then use the Replace() method or -replace operator as shown above to replace the old value with the new value:
      $fileContent = Get-Content "C:\path\to\your\file.txt"
      $fileContent = $fileContent.Replace($OldValue, $NewValue)
      or
      $fileContent = Get-Content "C:\path\to\your\file.txt"
      $fileContent = $fileContent -replace $OldValue, $NewValue

      Finally, use the Set-Content cmdlet to write the modified string back to the file:
      Set-Content "C:\path\to\your\file.txt" -Value $fileContent

     I hope this helps.

     

    Regards,

    Ruud

Resources