[英]Powershell wildcard / regex replace
I am trying to write a PowerShell script to update my .nuspec
file (nuget depdency) to the latest build version. 我正在尝试编写PowerShell脚本来将我的
.nuspec
文件(nuget depdency)更新为最新的构建版本。 I am having trouble with the wildcards though. 我遇到了通配符问题。
So I want to replace the version number of this line 所以我想替换这一行的版本号
<dependency id="MyCompany.Common" version="1.0.0.0" />
to a new version number, ie version 2.2.2.2 到新版本号,即版本2.2.2.2
<dependency id="MyCompany.Common" version="2.2.2.2" />
My current place method looks like this. 我目前的地方法看起来像这样。 Note I need a wildcard as I have multiple nuget packages in the solution I need to replace, all follow the format of
MyCompany.PackageName
注意我需要一个通配符,因为我需要替换的解决方案中有多个nuget包,都遵循
MyCompany.PackageName
的格式
$filecontent -replace 'id="MyCompany.*" version="*"', "$Version" | Out-File $file
But this actually ends up creating 但实际上这最终会产生
<dependency 2.2.2.21.0.0.0" />
How do I modify my regex to ensure it replaces the version number component only? 如何修改我的正则表达式以确保它仅替换版本号组件?
用。。。来代替
$filecontent -replace 'id="MyCompany(.*?)" version=".*?"', "id=`"MyCompany`$1`" version=`"$Version`"" | Out-File $file
I went with a simple use of a capture group so I don't lose the specificity of your regex, matches only strings with 'MyCompany.*' in id, but doesnt add a lot of complexity. 我简单地使用了一个捕获组,所以我不会失去你的正则表达式的特殊性,只匹配id中带有'MyCompany。*'的字符串,但不会增加很多复杂性。 I capture everything up to the opening quote in version and replace whatever is before the next quote with the new version number.
我将所有内容捕获到版本中的开头报价,并使用新版本号替换下一个报价之前的内容。
$test='<dependency id="MyCompany.Common" version="1.0.0.0" />'
$newVersion='2.2.2.2'
$test -replace "(id=`"MyCompany`..*`" version=)`"[^`"]*","`$1`"$newVersion"
<dependency id="MyCompany.Common" version="2.2.2.2" />
Tested in PS 4.0
在PS
4.0
测试过
Powershell oddities and fragile bits include: Powershell奇怪和脆弱的部分包括:
backtick to escape instead of \\
反引号逃脱,而不是
\\
regex must be in "double quotes" 正则表达式必须是“双引号”
must either use single quotes or escapes to have capture groups work in the replacement string 必须使用单引号或转义才能使捕获组在替换字符串中起作用
$s = '<dependency id="MyCompany.Common" version="2.2.2.2" />'
$s -replace 'version=".*"', 'version="1.2.3.4"'<dependency id="MyCompany.Common" version="1.2.3.4" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.