我有一个文件原型如下:
// <some stuff>
#define KEYWORD release01-11
// <more stuff>
如何删除与KEYWORD同一行中的最后两个字符并用两个不同的字符(在本例中为12)替换它们,以结束:
// <some stuff>
#define KEYWORD release01-12
// <more stuff>
我试图使用Clear-Content和Add-Content,但我不能让它做我需要的。替换这些符号后,文件的其余部分需要保持不变。有没有更好的选择?
使用-replace
regex运算符识别相关语句并替换/删除尾随的数字:
# read file into a variable
$code = Get-Content myfile.c
# replace the trailing -XX with 12 in all lines starting with `#define KEYWORD`, with
$code = $code -replace '(?<=#define KEYWORD .+-)d{2}s*$','12'
# write the contents back to the file
$code |Set-Content myfile.c
正则表达式结构(?<=...)
是一个积极的向后看-它确保以下表达式只匹配它后面的文本是#define KEYWORD
,后面跟着一些字符和-
的位置。
如果你想总是增加当前值(而不是仅仅用12
替换它),我们需要一些方法来检查和评估当前值在做替换之前。
[Regex]::Replace()
方法只允许:
# read file into a variable
$code = Get-Content myfile.c
$code = $code |ForEach-Object {
# Same as before, but now we can hook into the regex engine's substitution routine
[regex]::Replace($_, '(?<=#define KEYWORD .+-)d{2}s*$',{
param($m)
# extract the trailing numbers, convert to a numerical type
$value = $m.Value -as [int]
# increment the value
$value++
# return the new value
return $value
})
}
# write the contents back to the file
$code |Set-Content myfile.c
在PowerShell 6.1及更高版本中,-replace
操作符原生支持scriptblock替换:
$code = $code |ForEach-Object {
# Same as before, but now we can hook into the regex engine's substitution routine
$_ -replace '(?<=#define KEYWORD .+-)d{2}s*$',{
# extract the trailing numbers, convert to a numerical type
$value = $_.Value -as [int]
# increment the value
$value++
# return the new value
return $value
}
}