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

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

问题描述

我的工作是修改配置文件PowerShell脚本。我有这样的文件:

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

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

谁应该是这样的:

who should look like this:

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

如果有一个按键(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.

如果该键不(disablepostprocessing和segmentstarttimeout),附加键和值的文件。我的功能到目前为止是这样的:

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"


  • 什么是正确的正则表达式?

  • 我如何检查是否有更换?

  • 如果没有更换?我怎样才能加上$键+=+ $价值的文件,然后

  • 推荐答案

    假设 $键要替换始终处于一行的开头,而且它不包含特殊字符的正则表达式

    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" 
    

    如果没有替换 $键= $值将被添加到该文件。

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

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

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