Golang : Read a text file and replace certain words
Problem :
You have a text file with some words that you need to replace with another word.
Solution :
Use the bytes.Replace()
function. For example :
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
)
func main() {
input, err := ioutil.ReadFile("original.txt")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
output := bytes.Replace(input, []byte("replaceme"), []byte("ok"), -1)
if err = ioutil.WriteFile("modified.txt", output, 0666); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
original.txt
this is a text file that contains couple of replaceme words that need to be replaced.
for example, a replaceme word in this line
and another [replaceme] word in this line too
and after executing the above code
modified.txt
this is a text file that contains couple of ok words that need to be replaced.
for example, a ok word in this line
and another [ok] word in this line too
See also : Golang : Read file
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+26.3k Golang : Convert(cast) string to uint8 type and back to string
+25.2k Golang : Convert uint value to string type
+9.1k Golang : does not implement flag.Value (missing Set method)
+8k Golang : Get all countries phone codes
+10.2k Golang : Convert file content to Hex
+17.6k Golang : delete and modify XML file content
+8.1k Golang : Routes multiplexer routing example with regular expression control
+26.6k Golang : How to check if a connection to database is still alive ?
+13.3k Golang : Read from buffered reader until specific number of bytes
+13.5k Golang : reCAPTCHA example
+4.7k Facebook : How to place save to Facebook button on your website
+33.9k Golang : Proper way to set function argument default value