xml - 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 个?
解决方案
我通常同意应该使用 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-Content
or|Out-File
自己。
编辑:一个稍微简单的版本,需要 PSv3+ 作为Get-Content -raw
参数
powershell -Nop -C "$RE=[RegEx]'(?<=<version>).*(?=</version>)';$RE.Replace((gc '.\example.xml' -raw),'2.0.0',2)"
推荐阅读
- postgresql - 如何将数据从表 B 附加到表 A 但仅当表 C 中有记录时
- reactjs - 使用 Material UI Select 反应最终形式
- python - 如何在 ubuntu 14.04 上将 python3.6 设为默认值
- linux-kernel - 如果我的系统上安装了 512 MB 的物理内存,Linux 内核如何处理内存映射
- r - 有什么方法可以从 R 中的累积 PCA 图中选择前 n 个 PCA 组件?
- javascript - 将百分比编码的表情符号显示为 html
- powershell - 将字符串转换为数据类型以存储在哈希表中
- java - GetByteArrayElements 未在此范围内声明
- maxima - 在最大值中通过引用调用:可能吗?
- javascript - 提交表单时如何轻松阻止页面重新加载?