Replace a string in a Golang text file

How to replace a line in a text file with a new line?

Suppose I opened a file and each line in an array of string objects I now scroll through

//find line with ']' for i, line := range lines { if strings.Contains(line, ']') { //replace line with "LOL" ? } } 
+5
source share
1 answer

What matters here is not so much what you do in this cycle. It does not look like you will directly edit the file on the fly.

The easiest solution for you is to simply replace the string in the array and then write the contents of the array back to your file when you are done.

Here is the code I put together in a minute or two. It compiles correctly 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 is also (with the same code) https://gist.github.com/dallarosa/b58b0e3425761e0a7cf6

+11
source

Source: https://habr.com/ru/post/1203831/


All Articles