我正在尝试掏出类似于以下内容的东西:
diff <(echo -e "$string1" ) <(echo -e "$string2")
在 Golang 中,但我对 exec.Command
的所有尝试都失败了。
这是我尝试过的最幼稚的尝试(CombinedOutput
暂时用于获取底层问题):
func Diff(str1, str2 string) (string, error) {
cmd := exec.Command("diff", sanitize(str1), sanitize(str2))
bytes, err := cmd.CombinedOutput()
result := string(bytes)
if err != nil {
switch err.(type) {
case *exec.ExitError:
return result, nil
default:
return "", nil
}
}
return result, nil
}
这给了我这样的结果: diff:\"foo\nbar\nbaz\": No such file or directory
diff:\"foo\nfighters\nbaz\": 没有那个文件或目录
更复杂的版本仍然不起作用:
func Diff(str1, str2 string) (string, error) {
cmd := exec.Command("diff")
stdin, err := cmd.StdinPipe()
if err != nil {
return "", err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", err
}
err = cmd.Start()
if err != nil {
return "", err
}
io.WriteString(stdin, echoString(str1))
io.WriteString(stdin, echoString(str2))
bytes, err := ioutil.ReadAll(stdout)
cmd.Wait()
result := string(bytes)
if err != nil {
switch err.(type) {
case *exec.ExitError:
return result, nil
default:
return "", nil
}
}
return result, nil
}
func echoString(str string) string {
return fmt.Sprintf(`<( echo -e "%s" )`, strings.Replace(str, `"`, `\"`, -1))
}
根本没有输出,我得到 diff: missing operand after `diff'
diff:尝试 `diff --help' 获取更多信息。
在 stderr
中。
所以我认为我并不真的需要 echo
指令,因为我已经得到了字符串,所以我尝试用转义部分替换 echoString
实现,即 return strings.Replace(str, `"`, `\"`, -1)
但我得到了同样的错误。
有什么想法吗?
最佳答案
这是最简单的解决方案,只需将 diff
命令传递给 bash
shell:
cmd := exec.Command(
"bash", "-c",
fmt.Sprintf("diff <(echo -e %s) <(echo -e %s)", str1, str2))
关于在 Golang 中使用输入重定向来排除差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52998549/