调用exec.Command中的“sed”命令

huangapple go评论64阅读模式
英文:

Calling "sed" from exec.Command

问题

我目前在尝试运行这段代码时遇到了问题,它应该调用Unix命令sed来查找并替换文件./myfile.txt中的字符串hellogoodbye

如果你从命令行运行它,它可以正常工作,但是如果我尝试从我的Go代码中运行相同的命令...

command := exec.Command("sed", "-e \"s/hello/goodbye/g\" ./myfile.txt")
result,err := command.CombinedOutput()
fmt.Println(string(result))

但是我一直得到这个输出:

sed: -e expression #1, char 2: unknown command: `"'

是否有某种引号转义或其他导致它错误解释字符串的问题?

任何帮助将不胜感激。

英文:

I'm currently having trouble trying to run this code which is supposed to call the unix command sed to find and replace the string hello with goodbye in the file ./myfile.txt

This works fine if you run it from the command line, but if I try the same thing from my Go code....

command := exec.Command("sed", "-e \"s/hello/goodbye/g\" ./myfile.txt")
result,err := command.CombinedOutput()
fmt.Println(string(result))

Bit I just keep on getting this output

sed: -e expression #1, char 2: unknown command: `"'

Is there some sort of quote escaping going on or something to cause it to interpret the string wrong?

Any help would be appreciated

答案1

得分: 5

我相信以下代码可以工作:

command := exec.Command("sed", "-e","s/hello/goodbye/g","myfile.txt")
英文:

I believe the following works:

command := exec.Command("sed", "-e","s/hello/goodbye/g","myfile.txt")

huangapple
  • 本文由 发表于 2012年7月31日 21:10:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/11740887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定