1

I have a text file and want to regex/replace something with the content of a variable in PowerShell.

  • File: my.json
  • Variable in Powershell $version
  • Search for: version : "something"
  • Replace "something" with the content of the variable $version

Here is what I tried. Search and replace works as expected but the result is version : "$version".

(Get-Content my.json) -replace '(?<pre>"version"[\s]*:[\s]*)(?<V>"[^\"]*")', '$1"$version"' | Out-File my.json
2
  • Does this answer help at all? I think an escape sequence should alleviate your issue, either way. Commented Jul 26, 2016 at 14:13
  • Powershell has natively implements a JSON parser, you'd better use that if you can. Check out the ConvertFrom-JSON and ConvertTo-JSON methods Commented Jul 26, 2016 at 14:21

2 Answers 2

4

To be able to use variables in the replacement string you need to use a double-quoted replacement string, meaning that you need to escape backreferences and nested double quotes:

(Get-Content my.json) -replace '...', "`$1`"$version`"" | ...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer and the edit! Have a great day!
@dknaack if this answer solved your problem, please consider accepting it
2

Ansgar's answer is perfectly valid, but ` escape sequences can be ugly and hinder readability.

I would personally use the -f format operator to concatenate the '$1' string literal and the value of $version:

(Get-Content my.json) -replace '...',('$1{0}' -f $version)

1 Comment

Thanks! Looks better, yes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.