Tag Archives: golang

golang change text in file

This will replace string “katinas” with “super duper”.

package main

import (
"io/ioutil"
"log"
"strings"
)

func main() {

var file string
file = "test.txt"
input, err := ioutil.ReadFile(file)
if err != nil {
log.Fatalln(err)
}

lines := strings.Split(string(input), "\n")

for i, line := range lines {
if strings.Contains(line, "katinas") {
lines[i] = "super duper"
}
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile(file, []byte(output), 0644)
if err != nil {
log.Fatalln(err)
}
}