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
+12k Golang : Search and extract certain XML data example
+4.8k Python : Create Whois client or function example
+6.4k Golang : Reverse by word
+10.1k Generate Random number with math/rand in Go
+10.9k Use systeminfo to find out installed Windows Hotfix(s) or updates
+18.1k Golang : Implement getters and setters
+13.8k Golang : How to pass map to html template and access the map's elements
+38.9k Golang : Remove dashes(or any character) from string
+39.2k Golang : Convert to io.ReadSeeker type
+5.6k Golang : Function as an argument type example
+7.8k Golang : Find relative luminance or color brightness
+11.1k Golang : Fuzzy string search or approximate string matching example