Home > Software design >  PowerShell how to incorporate regex in replace command
PowerShell how to incorporate regex in replace command

Time:08-24

I have a txt file (TSTTTT.txt) with a string value of :

$$FULL_LOAD_DAY=Monday

I would like to change it to, through powershell :

$$FULL_LOAD_DAY=Tuesday

I already know that the regex needed to find my entire string is [regardless of the day]:

 \$\$FULL_LOAD_DAY=(\w )(?=[,.]|$)   

I just don't know how to change my usual Powershell command to include regex:

(Get-Content C:\Private\TSTTTT.txt).replace('a', 'b') | Set-Content C:\Private\TSTTTT.txt

CodePudding user response:

You can use the -replace operator to use regex in replacing string.

For example, to replace your string with 'b', use the following:

(Get-Content C:\Private\TSTTTT.txt) -replace '\$\$FULL_LOAD_DAY=(\w )(?=[,.]|$) ','b' | Set-Content C:\Private\TSTTTT.txt

CodePudding user response:

If I got it right your regex can be much simpler ...

$Day = 'Tuesday'
(Get-Content C:\Private\TSTTTT.txt) -replace '(?<=\$\$FULL_LOAD_DAY=)(\w )', $Day |
    Set-Content C:\Private\TSTTTT.txt
  • Related