Golang : Replace a parameter's value inside a configuration file example
Alright, putting this here for my own future reference. In this tutorial, we will explore how to read in a configuration(text) file, replace certain value of a parameter and write it back(update) into the file.
Basically, what this simple program does is to convert the entire configuration(text) file into a slice, scan for the parameter that we want to alter, update the parameter's value and write back to file.
Here you go!
package main
import (
"fmt"
"strings"
)
func main() {
input, err := ioutil.ReadFile(configFilename)
if err != nil {
log.Println(err)
}
// split into a slice
lines := strings.Split(string(input), "\n")
fmt.Println("before : ", lines)
// assuming that we want to change the value of thirdItem from 3 to 100
replacementText := "thirdItem = 100"
for i, line := range lines {
if equal := strings.Index(line, "thirdItem"); equal == 0 {
// update to the new value
lines[i] = replacementText
}
}
fmt.Println("after : ", lines)
// join back before writing into the file
linesBytes := []byte(strings.Join(lines, "\n"))
//the value will be UPDATED!!!
if err = ioutil.WriteFile(configFilename, linesBytes, 0666); err != nil {
log.Println(err)
}
}
You can play with a demo without modifying any file at https://play.golang.org/p/G8RKWdfh5hu
Hope this helps and happy coding!
References :
https://www.socketloop.com/references/golang-io-ioutil-writefile-function-example
https://www.socketloop.com/tutorials/golang-convert-string-to-byte-examples
See also : Golang : How to remove certain lines from a 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
+8.9k Golang : Create and shuffle deck of cards example
+51.1k Golang : Check if item is in slice/array
+7.1k Golang : How to detect if a sentence ends with a punctuation?
+16.2k Golang : How to implement two-factor authentication?
+23.2k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+5.4k Unix/Linux : How to find out the hard disk size?
+5.2k Golang : fmt.Println prints out empty data from struct
+8.1k Golang : Implementing class(object-oriented programming style)
+15.4k Golang : Get checkbox or extract multipart form data value example
+6.2k PHP : Proper way to get UTF-8 character or string length
+3.4k Java : Get FX sentiment from website example
+5.4k Golang : Frobnicate or tweaking a string example