Beispiele in GoLang#
Interpretieren: go run <file> Kompilieren: go build <file>
read file, modify it and write it back (28.12.2021)#
package main
// filemodify.go - read file, modify it and write it back
/*cat testdata/hello
hello gopher
hello helmut
*/
// inspired by:
// https://pkg.go.dev/io/ioutil#example-ReadFile on 20211228
// and
// https://www.geeksforgeeks.org/strings-replace-function-in-golang-with-examples/
import (
"fmt"
"io/ioutil"
"log"
"strings"
)
func main() {
content, err := ioutil.ReadFile("testdata/hello")
if err != nil {
log.Fatal(err)
}
//https://yourbasic.org/golang/convert-string-to-byte-slice/
//s := string([]byte{65, 66, 67, 226, 130, 172})
contentstring := string(content)
//strings.Replace(contentstring, "helmut", "hannelore", -1) // -1 replaces all
contentmodifiedstring := strings.Replace(contentstring, "h", "g", 2)
//strings.ReplaceAll(contentstring, "h", "g")
fmt.Printf("File contents:\n%s", contentmodifiedstring)
//b := []byte("ABC€")
contentbyte := []byte(contentmodifiedstring)
//func WriteFile(filename string, data []byte, perm fs.FileMode) error
errwrite := ioutil.WriteFile("testdata/hellomodified", contentbyte, 0644)
if err != nil {
log.Fatal(errwrite)
}
}
Fin