regex - Powershell 类 sed 操作
问题描述
考虑以下用例:我有一个这种格式的文件:
some_content
major_version=1
minor_version=33
some_other_content
combined_version=1.33
more_content
我想编写一个以 Major/Minor 作为参数的 Powershell 脚本,并增加文件中的相应数字。所以我尝试使用-replace
运算符。这就是我想出的:
# Let's say $Major and $Minor contains the updated numbers (I mean, I incremented one of them by 1, according to the user selection)
$SearchExpr = '(?s)(?<First>.*major\D+)\d+(?<Second>.*minor\D+)\d+(?<Third>.*combined\D+)\d+\.\d+'
$ReplaceExp = "`${First}${Major}`${Second}${Minor}`${Third}${Major}.${Minor}"
$VersionFileContent -replace $SearchExp, $ReplaceExp | Out-File $VersionFile
但这很讨厌。问题是,如果您知道文本,则在替换文本中的字符串时很容易,例如:
"Girrafe, Zebra, Dog" -replace 'Dog', 'Cat'
替换“'Zebra'之后的任何内容”更少..
想法?
解决方案
你可以switch -Regex -File
很容易地使用它:
$content = switch -Regex -File 'D:\Test\MyFile.txt' {
'^(major|minor)_version=(\d+)' {
'{0}_version={1}' -f $matches[1], ([int]$matches[2] + 1)
}
default { $_ }
}
# for safety, save to a new file
$content | Set-Content -Path 'D:\Test\MyUpdatedFile.txt' -Force
结果:
some_content
major_version=2
minor_version=34
some_other_content
combined_version=1.33
more_content
如果您还需要更新组合版本,请扩展为:
$content = switch -Regex -File 'D:\Test\MyFile.txt' {
'^(major_version)=(\d+)' {
$major = [int]$matches[2] + 1
'{0}={1}' -f $matches[1], $major
}
'^(minor_version)=(\d+)' {
$minor = [int]$matches[2] + 1
'{0}={1}' -f $matches[1], $minor
}
'^(combined_version)=(\d+)' {
'{0}={1}.{2}' -f $matches[1], $major, $minor
}
default { $_ }
}
$content | Set-Content -Path 'D:\Test\MyUpdatedFile.txt' -Force
推荐阅读
- php - 如何使用 jinja2 在 /etc/bind 文件中增加 Serial
- javascript - 计算页面上断开链接的数量
- synchronization - AAD 组和 MS 团队同步太慢
- visual-studio-code - Visual Studio Code 中模块导入的未解决导入
- linux - 在 bash 中使用 while 循环 awk?
- arrays - ksh 中一个键的多个值
- asp.net-web-api - F# 中的模型域分离和 Automapper
- stackdriver - 是否可以在本地机器中使用 stackdriver 监控?
- c# - 如何在 Unity 中仅更改单个字母的颜色?
- node.js - Notejs:如何将传入的网络数据包转换为流对象?