加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – 用于替换或添加文本文件中的行的Powershell函数

发布时间:2020-12-13 21:53:21 所属栏目:百科 来源:网络整理
导读:我正在研究修改配置文件的power shell脚本.我有这样的文件: ###################################################### comment about logentrytimeout#####################################################Logentrytimeout= 1800 谁应该是这样的: ######
我正在研究修改配置文件的power shell脚本.我有这样的文件:
#####################################################
# comment about logentrytimeout
#####################################################
Logentrytimeout= 1800

谁应该是这样的:

#####################################################
# comment about logentrytimeout
#####################################################
Logentrytimeout= 180
disablepostprocessing = 1
segmentstarttimeout = 180

如果存在密钥集(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"

>正确的正则表达式是什么?
>如何检查是否有更换?
>如果没有替换:如何将$key“=”$值附加到文件中?

假设您要替换的$key始终位于一行的开头,并且它不包含特殊的正则表达式字符
function setConfig( $file,$value ) {
    $content = Get-Content $file
    if ( $content -match "^$keys*=" ) {
        $content -replace "^$keys*=.*","$key = $value" |
        Set-Content $file     
    } else {
        Add-Content $file "$key = $value"
    }
}

setConfig "divider.conf" "Logentrytimeout" "180"

如果没有替换,则$key = $value将附加到文件中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读