首页 > 解决方案 > 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'之后的任何内容”更少..

想法?

标签: regexpowershell

解决方案


你可以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

推荐阅读