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
+5.7k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+6.1k Golang : Calculate US Dollar Index (DXY)
+17k Golang : Find file size(disk usage) with filepath.Walk
+13.4k Golang : Strings comparison
+39.9k Golang : UDP client server read write example
+8.1k Swift : Convert (cast) Character to Integer?
+14k Golang : Check if a file exist or not
+11.5k Golang : Find age or leap age from date of birth example
+5.2k Golang : Generate Interleaved 2 inch by 5 inch barcode
+19.1k Golang : Delete item from slice based on index/key position
+11.8k Golang : How to parse plain email text and process email header?
+21.4k Golang : Encrypt and decrypt data with TripleDES