英文:
golang command not working even though manually executing it does
问题
我正在尝试在我的Go程序中执行一个awk
命令(该命令从一个包含加利福尼亚州邮政编码的制表符分隔文件中提取指定城市(此处为旧金山)的邮政编码):
cmd := exec.Command(
"awk",
"-F",
"'\\t'",
"'{if ($4 == \"SAN FRANCISCO\") print $0; }'",
"zipcodes_ca.txt",
)
fmt.Println(cmd.Args)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
return
}
这将输出:
[awk -F '\t' '{if ($4 == "SAN FRANCISCO") print $0; }' zipcodes_ca.txt]
exit status 2: awk: syntax error at source line 1
context is
>>> ' <<<
awk: bailing out at source line 1
如果我将命令打印出来,并将其作为命令运行awk -F '\t' '{if ($4 == "SAN FRANCISCO") print $0; }' zipcodes_ca.txt
,它可以正常工作。但是,通过我的Go程序运行时似乎出现了问题。我不确定我在这里做错了什么。我猜测我可能没有正确转义一些内容,但是我尝试的所有方法似乎都不起作用。
英文:
I'm trying to execute an awk
command in my go program (the awk command pulls zip codes for a specified city, San Francisco in this case, from a tab delimited file of California zip codes):
cmd := exec.Command(
"awk",
"-F",
"'\\t'",
"'{if ($4 == \"SAN FRANCISCO\") print $0; }'",
"zipcodes_ca.txt",
)
fmt.Println(cmd.Args)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
return
}
This outputs:
[awk -F '\t' '{if ($4 == "SAN FRANCISCO") print $0; }' zipcodes_ca.txt]
exit status 2: awk: syntax error at source line 1
context is
>>> ' <<<
awk: bailing out at source line 1
If I take the printed args from the command and just run that as a command awk -F '\t' '{if ($4 == "SAN FRANCISCO") print $0; }' zipcodes_ca.txt
it works. But, running it through my go program seems to be having issues. I'm not sure what I'm doing wrong here. I'm guessing I'm escaping things incorrectly, but nothing I try seems to work.
答案1
得分: 9
我认为你不需要在参数周围使用单引号。它们是使用 shell 时的一个产物,可以防止 shell 解释参数内容。尝试不使用它们。
英文:
I don't think that you need single quotes around arguments. They are an artifact of using shell that prevents shell from interpreting argument content. Try without them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论