I am trying to source the /etc/environment
file using golang. I parsed each line of the file and used the following piece of code:
var myExp = regexp.MustCompile(`(?P<first>.*)=(?P<second>.*)`)
to get key=value from the file. But some values have =
in it and the above regex fails.
For example, one of the lines in the environment would look like: CONFIG_BASE64=SDFSWESC1=
and I want it to be separated by the first occurence of =
. i.e, Key isCONFIG_BASE64
and Value is SDFSWESC1=
What's wrong with strings.SplitN()
? Going to regex seems overkill for this.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
file, err := os.Open("/etc/environment")
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
// MAGIC
split := strings.SplitN(scanner.Text(), "=", 2)
// Line didn't have an = in it
if len(split) < 2 {
continue
}
// Skip comments, pretty naive though
if strings.HasPrefix(split[0], "#") {
continue
}
fmt.Printf("key %s value %s
", split[0], split[1])
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}