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
+10.5k Golang : Convert IPv4 address to packed 32-bit binary format
+15.7k Golang : Get command line arguments
+10.4k Golang : How to check if a string starts or ends with certain characters or words?
+4.1k Golang : What is StructTag and how to get StructTag's value?
+6.9k Golang : Generate random Chinese, Japanese, Korean and other runes
+6k Golang : Get all countries phone codes
+5.3k Golang : Levenshtein distance example
+26.1k Golang : How to verify uploaded file is image or allowed file types
+5.5k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+8.7k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+11.6k Golang : Chunk split or divide a string into smaller chunk example
+6.2k Gogland : Where to put source code files in package directory for rookie