mle*_*les 6 regex powershell replace append
我正在研究修改配置文件的powershell脚本.我有这样的文件:
#####################################################
# comment about logentrytimeout
#####################################################
Logentrytimeout= 1800
Run Code Online (Sandbox Code Playgroud)
谁应该是这样的:
#####################################################
# comment about logentrytimeout
#####################################################
Logentrytimeout= 180
disablepostprocessing = 1
segmentstarttimeout = 180
Run Code Online (Sandbox Code Playgroud)
如果存在密钥集(Logentrytimeout),只需将其更新为给定值即可.忽略注释,其中提到了键(以#开头的行).密钥不区分大小写.
如果未设置密钥(disablepostprocessing和segmentstarttimeout),请将密钥和值附加到文件.到目前为止我的功能是这样的:
function setConfig( $file, $key, $value )
{
(Get-Content $file) |
Foreach-Object {$_ -replace "^"+$key+".=.+$", $key + " = " + $value } |
Set-Content $file
}
setConfig divider.conf "Logentrytimeout" "180"
setConfig divider.conf "disablepostprocessing" "1"
setConfig divider.conf "segmentstarttimeout" "180"
Run Code Online (Sandbox Code Playgroud)
Mik*_*keM 14
假设$key你想要替换总是在一行的开头,并且它不包含特殊的正则表达式字符
function setConfig( $file, $key, $value ) {
$content = Get-Content $file
if ( $content -match "^$key\s*=" ) {
$content -replace "^$key\s*=.*", "$key = $value" |
Set-Content $file
} else {
Add-Content $file "$key = $value"
}
}
setConfig "divider.conf" "Logentrytimeout" "180"
Run Code Online (Sandbox Code Playgroud)
如果没有替换$key = $value将被附加到文件中.