string - 替换文本文件中一行的值

标签 string powershell replace text-files

我目前正在编辑文本文件的一行。当我尝试覆盖文本文件时,文本文件中只返回一行。我正在尝试用

调用该函数
modifyconfig "test" "100"

config.txt:

check=0
test=1

modifyConfig() function:

Function modifyConfig ([string]$key, [int]$value){
    $path = "D:\RenameScript\config.txt"

    ((Get-Content $path) | ForEach-Object {
        Write-Host $_
        # If '=' is found, check key
        if ($_.Contains("=")){
            # If key matches, replace old value with new value and break out of loop
            $pos = $_.IndexOf("=")
            $checkKey = $_.Substring(0, $pos)
            if ($checkKey -eq $key){
                $oldValue = $_.Substring($pos+1)
                Write-Host 'Key: ' $checkKey
                Write-Host 'Old Value: ' $oldValue
                $_.replace($oldValue,$value)
                Write-Host "Result:" $_
            }
        } else {
            # Do nothing
        }
    }) | Set-Content ($path)
}

我在 config.txt 中收到的结果:

test=100

我缺少“check=0”。

我错过了什么?

最佳答案

$_.replace($oldValue,$value) 在你最里面的条件替换 $oldValue$value 然后打印修改字符串,但您没有代码打印不匹配的字符串。因此,只有修改后的字符串被写回 $path

替换行

# Do nothing

$_

并且还向内部条件添加一个带有 $_else 分支。

或者您可以将 $_ 分配给另一个变量并像这样修改您的代码:

Foreach-Object {
    $line = $_
    if ($line -like "*=*") {
        $arr = $line -split "=", 2
        if ($arr[0].Trim() -eq $key) {
            $arr[1] = $value
            $line = $arr -join "="
        }
    }
    $line
}

关于string - 替换文本文件中一行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17099177/

相关文章:

python - 尝试对 Pandas 使用替换方法

java - 使用 for 循环迭代 HashSet

java - Struts 1 ActionForm 中的处理日期

c++ - 为什么 ("Maya"== "Maya") 在 C++ 中不是真的?

perl - 在Perl或PowerShell中使用增量文件更新记录

powershell - 字符串替换在运行时在 powershell 脚本中不起作用

python - Polars - 用其他列的值替换列中的部分字符串

javascript - 如何防止子字符串结束父字符串?

powershell - 在不满足密码复杂性的情况下创建了 New-LocalUser

Python - 返回一个字符串的函数,该字符串删除了另一个字符串中的字符