Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing value on one line in a text file

I am currently working on editing one line of a text file. When I try to overwrite the text file, I only get one line back in the text file. I am trying to call the function with

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)
}

The result I receive in my config.txt:

test=100

I am missing "check=0".

What have I missed?

like image 743
Aero Chocolate Avatar asked Sep 05 '25 03:09

Aero Chocolate


1 Answers

$_.replace($oldValue,$value) in your innermost conditional replaces $oldValue with $value and then prints the modified string, but you don't have code printing non-matching strings. Because of that only the modified string are written back to $path.

Replace the line

# Do nothing

with

$_

and also add an else branch with a $_ to the inner conditional.

Or you could assign $_ to another variable and modify your code like this:

Foreach-Object {
    $line = $_
    if ($line -like "*=*") {
        $arr = $line -split "=", 2
        if ($arr[0].Trim() -eq $key) {
            $arr[1] = $value
            $line = $arr -join "="
        }
    }
    $line
}
like image 165
Ansgar Wiechers Avatar answered Sep 09 '25 07:09

Ansgar Wiechers