我正在编写一个修改配置文件的 powershell 脚本。我有这样的文件:
#####################################################
# comment about logentrytimeout
#####################################################
Logentrytimeout= 1800
谁应该看起来像这样:
#####################################################
# comment about logentrytimeout
#####################################################
Logentrytimeout= 180
disablepostprocessing = 1
segmentstarttimeout = 180
如果有key设置(Logentrytimeout),只需将其更新为给定值即可。忽略提到关键的注释(以 # 开头的行)。 key 不区分大小写。
如果未设置键(禁用后处理和段开始超时),则将键和值 append 到文件中。到目前为止我的功能是这样的:
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"
- 正确的正则表达式是什么?
- 如何检查是否有替代品?
- 如果没有替换:那么如何将 $key+"= "+$value append 到文件中?
最佳答案
假设您要替换的$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"
如果没有替换$key = $value
将被追加到文件中。
关于regex - Powershell函数在文本文件中替换或添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15662799/