2 回答
TA贡献1982条经验 获得超2个赞
这是一个准系统示例,让您了解如何处理 os.Args
$ go run main.go --foo asdf --bar xxx --baz ccc
map[--foo:asdf --bar:xxx --baz:ccc]
jsandrew-Mac:osarg jsandrew$ cat main.go
package main
import (
"fmt"
"os"
)
func manyRandomArg() map[string]string {
rv := make(map[string]string)
for ix, x := range os.Args {
if x[:2] == "--" {
rv[x] = os.Args[ix+1]
}
}
return rv
}
func main() {
fmt.Printf("%v\n", manyRandomArg())
}
TA贡献1779条经验 获得超6个赞
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
var key0, key1, key2, key3, key4, filename string
var fileext = regexp.MustCompile(`([a-z]+)\.yaml`)
func manyRandomArg() map[string]string {
rv := make(map[string]string)
for ix, x := range os.Args {
if x[:2] == "--" {
rv[x] = os.Args[ix+1]
}
}
return rv
}
func main() {
fmt.Printf("\n%v\n", manyRandomArg())
readargs()
}
func readargs() {
rv := manyRandomArg()
keys := make([]string, 0, len(rv))
for key, _ := range rv {
keys = append(keys, key)
}
// Convert map to slice of values.
values := []string{}
for _, value := range rv {
values = append(values, value)
}
for keys, values := range rv {
fmt.Printf("key[%s] value[%s]\n", keys, values)
}
if fileext.MatchString(values[0]) {
fmt.Printf("Value %s\n", values[0])
filename = values[0]
} else if fileext.MatchString(values[1]) {
fmt.Printf("Value %s\n", values[1])
filename = values[1]
} else if fileext.MatchString(values[2]) {
fmt.Printf("Value %s\n", values[2])
filename = values[2]
} else if fileext.MatchString(values[3]) {
fmt.Printf("Value %s\n", values[3])
filename = values[3]
} else if fileext.MatchString(values[4]) {
fmt.Printf("Value %s\n", values[4])
filename = values[4]
} else {
log.Fatal("index 4 fail")
os.Exit(1)
}
b, err := ioutil.ReadFile(filename) // just pass the file name
if err != nil {
fmt.Print(err)
}
str := string(b) // convert content to a 'string'
key0 = trimLeftChars(keys[0], 2)
key1 = trimLeftChars(keys[1], 2)
key2 = trimLeftChars(keys[2], 2)
key3 = trimLeftChars(keys[3], 2)
key4 = trimLeftChars(keys[4], 2)
// Create replacer with pairs as arguments.
r := strings.NewReplacer(key0, values[0], key1, values[1], key2, values[2], key3, values[3], key4, values[4])
// Replace all pairs.
result := r.Replace(str)
fmt.Println(result)
newContents := []byte(result)
err = ioutil.WriteFile("new3.yaml", newContents, 0664)
if err != nil {
panic(err)
}
}
func trimLeftChars(s string, n int) string {
m := 0
for i := range s {
if m >= n {
return s[i:]
}
m++
}
return s[:0]
}
- 2 回答
- 0 关注
- 100 浏览
添加回答
举报