背景
主要记录一下怎么用 Golang 的 os/exec 去执行一个 cmd 的 pipeline,就是拿 cmdA 的输出作为 cmdB 的输入,这里记录了两种方法去替换文件里面的字符串。 pipe 那个逻辑在 demo1 里。 另外一种是直接读文件做替换,一不小心两个都放进来了。
代码
package mainimport ("fmt""os""os/exec""path/filepath""regexp""strings"
)// *java.Objectfunc main() {// 定义正则表达式regex := regexp.MustCompile(`\*java\.Object\b`)// 要替换的字符串data := "var obj *java.Object"// 替换字符串data = regex.ReplaceAllString(data, "java.Object")// 打印替换后的字符串fmt.Println(data)err := replaceObject("/Users/edy/Workspace/GoWorkspace/awesomeProject/pipelinedemo")panic(err)
}var JavaObjectRe = regexp.MustCompile(`b\*java\.Object`)func replaceObject(path string) error {fs, err := os.ReadDir(path)if err != nil {return err}for _, f := range fs {fileName := filepath.Join(path, f.Name())if f.IsDir() {if err = replaceObject(fileName); err != nil {return err}} else if strings.HasSuffix(f.Name(), ".go") {data, err := os.ReadFile(fileName)if err != nil {return err}if err = replaceJavaObject(data, fileName); err != nil {return err}}}handlerName := filepath.Join(path, "handler.go")handler, err := os.ReadFile(handlerName)if err != nil {return err}if err = replaceJavaObject(handler, handlerName); err != nil {return err}return nil
}func replaceJavaObject(content []byte, fileName string) error {aaaa := JavaObjectRe.Find(content)println(string(aaaa))content = JavaObjectRe.ReplaceAll(content, []byte("java.Object"))err := os.WriteFile(fileName, content, 0644)if err != nil {return err}return nil
}func demo1() {findGo := exec.Command("find", ".", "-name", "*.go")sout, err := findGo.StdoutPipe()if err != nil {panic(err)return}bakGo := exec.Command("xargs", "sed", "-i", "-bak", "-e", "s/\\*java\\.Object/java\\.Object/g")bakGo.Stdin = soutbakGo.Stdout = os.Stdouterr = findGo.Start()if err != nil {panic(err)}err = bakGo.Start()if err != nil {panic(err)}err = findGo.Wait()if err != nil {panic(err)}err = bakGo.Wait()if err != nil {panic(err)}
}