Powershell如何仅替换给定数量的火柴?

时间:2018-09-07 14:28:05

标签: xml powershell batch-file windows-10

我正在尝试在Windows 10上编写批处理脚本。

在XML文件中,我有多个“版本”标签。使用powershell,我只希望替换其中的前2个。

powershell -Command "(gc example.xml) -replace '(?s)<version>.*?</version>', '<version>2.0.0</version>' | Out-File example.xml"

但是此代码替换了所有代码。我怎样才能只替换其中的两个?

1 个答案:

答案 0 :(得分:0)

我通常同意应使用xml工具来编辑xml文件,
而且我认为不可能将其塞入一个直线中-但是interesting link gvee provided将其转换为example.xml

> type .\example.xml
<version>1.0.1</version>
<version>1.0.2</version>
<version>1.0.3</version>
<version>1.0.4</version>

powershell -Nop -C "$RE=[RegEx]'(?<=<version>).*(?=</version>)';$RE.Replace([string]::Join(\"`n\",(gc '.\example.xml')),'2.0.0',2)"

<version>2.0.0</version>
<version>2.0.0</version>
<version>1.0.3</version>
<version>1.0.4</version>

自己添加|Set-Content|Out-File

编辑:一个稍微简单的版本,其Get-Content -raw参数需要PSv3 +

powershell -Nop -C "$RE=[RegEx]'(?<=<version>).*(?=</version>)';$RE.Replace((gc '.\example.xml' -raw),'2.0.0',2)"