How to read a line from a file and replace it?

Hello, can anyone tell me that how can i read a file from a file and also how can i replace a file in a file.
bere are the texts of file :

sharedip=x.x.x.x
build=5.114
version=5.0

first of all, i want to read version from this file and store it in a variable.
then after that, i want to replace version with the text i stored in variable.

like, first i read version=5.0 from the file then after some time like after updating software version will be changed to 5.1 so i want to replace that 5.1 with 5.0
is there any method to do that?

What have you tried so far? Your description is not far from “pseudocode” that you could keep working on to get real Go code.

i want to replace these string,
i have tried reading lines and storing their text in a variable.
Like this :

fileIO, err := os.OpenFile("my.txt", os.O_RDWR, 0600)
            if err != nil {
            fmt.Println("Error ELOP0 ! Contact Support")

        }

        defer fileIO.Close()

        rawBytes, err := ioutil.ReadAll(fileIO)

        if err != nil {

            fmt.Println("Error EROP99X! Contact Support")

        }

        lines := strings.Split(string(rawBytes), "\n")

        for i, line := range lines {

            if i == 27 {

                defowner = line

            }

        }

but the issue here is sometimes maybe there is a space between these lines or maybe any line is on the top or on the bottom or middle so the result is not correct.

i have searched a lot but didn’t find any proper way to read values from a text file.

the thing i want to do is :

this is the text of hello.txt file :

sharedip=x.x.x.x
build=5.114
version=5.0

i want to read sharedip in a variable , so maybe shared IP is at the bottom or after build so it’s not possible to get accurate result from the way i tried.

is there any other method?

In the code, you have:

Which means “use the 28th line as defowner,” but based on your description, it sounds like that’s not actually the condition you want. It sounds like the condition should be more like "if line starts with "sharedip", then use that as the defowner. To do that, change your condition to:

for i, line := range lines {
    if strings.HasPrefix(line, "sharedip") {
        defowner = line
    }
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.