Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a line in text file Golang

Tags:

How do I replace a line in a text file with a new line?

Assume I've opened the file and have every line in an array of string objects i'm now looping through

//find line with ']'
    for i, line := range lines {

        if strings.Contains(line, ']') {


            //replace line with "LOL"
            ?
        }
    }
like image 487
sourcey Avatar asked Oct 02 '14 00:10

sourcey


People also ask

How do I read a file in Golang?

The simplest way of reading a text or binary file in Go is to use the ReadFile() function from the os package. This function reads the entire content of the file into a byte slice, so you should be careful when trying to read a large file - in this case, you should read the file line by line or in chunks.

How do you create a file in go?

In golang, use the os package and use the os. Create() function to create a file. We can open the file using os. Open() function.


1 Answers

What matters here is not so much what you do in that loop. It's not like you're gonna be directly editing the file on the fly.

The most simple solution for you is to just replace the string in the array and then write the contents of the array back to your file when you're finished.

Here's some code I put together in a minute or two. It properly compiles and runs on my machine.

package main

import (
        "io/ioutil"
        "log"
        "strings"
)

func main() {
        input, err := ioutil.ReadFile("myfile")
        if err != nil {
                log.Fatalln(err)
        }

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

        for i, line := range lines {
                if strings.Contains(line, "]") {
                        lines[i] = "LOL"
                }
        }
        output := strings.Join(lines, "\n")
        err = ioutil.WriteFile("myfile", []byte(output), 0644)
        if err != nil {
                log.Fatalln(err)
        }
}

There's a gist too (with the same code) https://gist.github.com/dallarosa/b58b0e3425761e0a7cf6

like image 89
DallaRosa Avatar answered Oct 06 '22 08:10

DallaRosa