哆啦的时光机
package mainimport ( "fmt" "io/ioutil" "log" "os" "regexp" "strings")var key0, key1, key2, key3, key4, filename stringvar 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]}