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"
?
}
}
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With