用于替换或添加文本文件中的行的 Powershell 函数 [英] Powershell function to replace or add lines in text files

查看:24
本文介绍了用于替换或添加文本文件中的行的 Powershell 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个修改配置文件的 powershell 脚本.我有这样的文件:

I'm working on a powershell script that modifies config files. I have files like this:

#####################################################
# comment about logentrytimeout
#####################################################
Logentrytimeout= 1800

谁应该看起来像这样:

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

如果有一个key set(Logentrytimeout),就将它更新为给定的值.忽略提及键的注释(以# 开头的行).密钥不区分大小写.

If there is a key set(Logentrytimeout), just update it to the given value. Ignore comments, where the key is mentioned(lines that start with #). The Key is case insensitive.

如果未设置键(禁用后处理和段启动超时),则将键和值附加到文件中.到目前为止,我的功能是这样的:

If the key is not set(disablepostprocessing and segmentstarttimeout), append key and value to the file. My function so far goes like this:

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 附加到文件中?
  • 推荐答案

    假设您要替换的 $key 始终位于行首,并且不包含特殊的正则表达式字符

    Assuming the $key you want to replace is always at the beginning of a line, and that it contains no special regex characters

    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 将被附加到文件中.

    If there is no replacement $key = $value will be appended to the file.

    这篇关于用于替换或添加文本文件中的行的 Powershell 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆