仅替换第一次出现

时间:2016-08-09 10:04:13

标签: json regex powershell powershell-v2.0 powershell-v3.0

我有一个替换的PowerShell脚本

"version" : "xxx"

"version" : "myBuildNumber"

现在我遇到了我的文件中有多个这些。 我只想替换第一次出现。

我已经尝试Powershell - Replace first occurences of String,但它不适用于我的正则表达式。

这是我的剧本:

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

1 个答案:

答案 0 :(得分:2)

由于您正在修补JSON文件,因此无法使用正则表达式。相反,您应该解析JSON,访问并更改所需的属性并将其写回:

$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
相关问题