Search code examples
regexstringpowershellparsingtext

looking for RexEx to replace a string within a string


I have to replace a string in a text file with Powershell. The text file has this content:

app.framework.locale=de_DE
app.gf.data.profile=somevalues,somevalues[,...]
app.gf.data.profile.path=C:\somepath\somesubpath
app.basket.currencies=currencies

I want to set the profile and the profile.path. So everything behind the "=" should be replaced, regardless of how long the string behind the "=" is.

I am reading the file, replacing the string, and writing back the file with these commands:

change the profile:

(Get-Content $TXT_FILE ).Replace('app.gf.data.profile=default,',"app.gf.data.profile=default,$Man") | Out-File $TXT_FILE -Encoding ASCII

change the profile path:

(Get-Content $TXT_FILE ).Replace('app.gf.data.profile.path=',"app.gf.data.profile.path=$Path") | Out-File $TXT_FILE -Encoding ASCII

As you can see, my replacement script is not correct, the rest behind the "=" will remain. I think I need a regex or some kind of wildcards to fit my needs.


Solution

  • You need to use

    (Get-Content $TXT_FILE) `
      -replace '^(app\.gf\.data\.profile=).*', "`$1,$Man" `
      -replace '^(app\.gf\.data\.profile\.path=).*', "`${1}$Path" | `
    Out-File $TXT_FILE -Encoding ASCII
    

    Here, -replace is used to enable regex replacing, and both regular expressions follow a similar logic:

    • ^ - matches start of a line
    • (app\.gf\.data\.profile=) - captures a literal string (literal dots in regex must be escaped) into Group 1 ($1 or ${1})
    • .* - matches the rest of the line.

    ${1} is used in the second case as the variable $Path follows the backreference immediately, and if it starts with a digit, the replacement will not be as expected.