dknaack dknaack - 6 months ago 89
JSON Question

Replace only first occurrence

I have a PowerShell scripts wich replaces

"version" : "xxx"


"version" : "myBuildNumber"

Now I encountered that I have multiple of these in my file.
I only want to replace the first occurrence.

I tried already Powershell - Replace first occurences of String but it does not work with my regex.

Here's my script:

(Get-Content myFile.txt) -replace '(?<pre>"version"[\s]*:[\s]*)(?<V>"[^\"]*")', "`$1`"$Env:BUILD_VERSION`"" | Out-File myFile.txt


Since you are patching a JSON file, regex isn't the way to go. Instead you should parse the JSON, access and change the property you want and write it back:

$filePath = 'your_Path_To_project.json'
$json = (Get-Content $filePath -raw | ConvertFrom-Json)
$json.version = $Env:BUILD_VERSION
$json | ConvertTo-Json -Depth 10 | Set-Content $filePath