用类似bash的环境变量引用对字符串进行插值 [英] Interpolate a string with bash-like environment variables references
问题描述
我的Golang CLI工具有一个输入字符串,其中包含对bash语法中的环境变量的一些引用( $ VAR
和 $ {VAR}
),例如:
I have an input string for my Golang CLI tool with some references to environment variables in bash syntax ($VAR
and ${VAR}
), e.g.:
$HOME/somedir/${SOME_VARIABLE}dir/anotherdir-${ANOTHER_VARIABLE}
通过替换environemnt插值此字符串的最有效方法是什么变量引用与实际值?
对于前面的示例,它可以是:
What is the most efficient way to interpolate this string by replacing environemnt variables references with actual values? For previous example it can be:
/home/user/somedir/4dir/anotherdir-5
如果 HOME = / home / user
, SOME_VARIABLE = 4
和 ANOTHER_VARIABLE = 5
。
现在我正在使用类似的东西:
Right now I'm using something like:
func interpolate(str string) string {
for _, e := range os.Environ() {
parts := strings.SplitN(e, "=", 2)
name, value := parts[0], parts[1]
str = strings.Replace(str, "$" + name, value, -1)
}
return str
}
,但是此代码无法处理 $ {}
变量。
but this code doesn't handle ${}
variables.
推荐答案
使用 os。 ExpandEnv :
s := os.ExpandEnv(
"$HOME/somedir/${SOME_VARIABLE}dir/anotherdir-${ANOTHER_VARIABLE}")
您可以使用 os.Expand (如果未从环境变量中获取值):
You can use os.Expand for the case where the values are not taken from environment variables:
m := map[string]string{
"HOME": "/home/user",
"SOME_VARIABLE": "4",
"ANOTHER_VARIABLE": "5",
}
s := os.Expand(
"$HOME/somedir/${SOME_VARIABLE}dir/anotherdir-${ANOTHER_VARIABLE}",
func(s string) string { return m[s] })
这篇关于用类似bash的环境变量引用对字符串进行插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!