【问题标题】:Replace only first occurrence仅替换第一次出现
【发布时间】:2016-12-15 07:45:53
【问题描述】:

我有一个替换的 PowerShell 脚本

"version" : "xxx"

"version" : "myBuildNumber"

现在我发现我的文件中有多个这样的文件。 我只想替换第一个匹配项。

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

这是我的脚本:

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

【问题讨论】:

  • 何乐而不为,同样的方法,只是使用一个DOTALL修饰符:(Get-Content myFile.txt) -replace '(?s)(?&lt;pre&gt;"version"\s*:\s*)(?&lt;V&gt;"[^"]*")(.*)', "`$1`"$Env:BUILD_VERSION`"`$3" | Out-File myFile.txt
  • 你尝试修改一个json吗?
  • 是的,来自 dotnet core 的 project.json

标签: json regex powershell powershell-2.0 powershell-3.0


【解决方案1】:

由于您正在修补 JSON 文件,因此 regex 不是要走的路。相反,您应该解析 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

【讨论】:

  • 默认情况下 ConvertTo-Json 将低于 3 的层次结构级别转换为字符串。添加 -Depth 10 之类的内容以保留更深层次的内容。
  • @AnsgarWiechers 感谢您的提示,没想到。
  • @dknaack 您需要用分号分隔语句:$json = (Get-Content 'projectJsonPath.json' -raw | ConvertFrom-Json); $json.version = $Env:BUILD_VERSION; $json | ConvertTo-Json -d | Set-Content 'projectJsonPath.json' 但是,我不会使用它,因为它会降低可读性和可维护性并且不是一个好习惯......我会改为创建一个函数Patch-Version,它将 JSON 路径和实际版本作为参数,以进一步提高可读性。
猜你喜欢
  • 1970-01-01
  • 2014-01-28
  • 2023-01-08
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多