【问题标题】:Sourcing the `/etc/environment` in Go在 Go 中采购 `/etc/environment`
【发布时间】:2018-11-30 00:02:57
【问题描述】:

我正在尝试使用 golang 获取 /etc/environment 文件。 我解析了文件的每一行并使用了以下代码:

var myExp = regexp.MustCompile(`(?P<first>.*)=(?P<second>.*)`) 从文件中获取 key=value。但是有些值中有=,上面的正则表达式失败了。

例如,环境中的一行代码如下所示: CONFIG_BASE64=SDFSWESC1= 我希望它被= 的第一次出现分开。即,Key 为CONFIG_BASE64,Value 为SDFSWESC1=

【问题讨论】:

  • 您想从CONFIG_BASE64=SDFSWESC1= 中检索CONFIG_BASE64 作为键和SDFSWESC1= 作为值。如果我的理解是正确的,那又如何呢? (?P<first>.*?)=(?P<second>.*)
  • 看起来有效。谢谢。
  • 很高兴您的问题得到了解决。感谢您的回复。

标签: python regex go pattern-matching environment-variables


【解决方案1】:

strings.SplitN() 有什么问题?使用正则表达式似乎有点过头了。

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\n", split[0], split[1])
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2013-10-06
    • 2018-04-15
    • 2012-12-20
    • 1970-01-01
    • 2014-11-18
    • 2011-03-20
    相关资源
    最近更新 更多