首页 > 解决方案 > Powershell如何仅替换给定数量的匹配项?

问题描述

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

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

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

但是这段代码替换了所有这些。我怎样才能只更换其中的 2 个?

标签: xmlpowershellbatch-filewindows-10

解决方案


我通常同意应该使用 xml 工具编辑 xml 文件,
并且我认为不可能将它塞进一个衬里 - 但是gvee 提供的有趣链接改变了这一点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-Contentor|Out-File自己。

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

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

推荐阅读