尽管手动执行,但Golang命令无法正常工作。

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

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(
	&quot;awk&quot;,
	&quot;-F&quot;,
	&quot;&#39;\\t&#39;&quot;,
	&quot;&#39;{if ($4 == \&quot;SAN FRANCISCO\&quot;) print $0; }&#39;&quot;,
	&quot;zipcodes_ca.txt&quot;,
)
fmt.Println(cmd.Args)

var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &amp;out
cmd.Stderr = &amp;stderr

err := cmd.Run()
if err != nil {
	fmt.Println(fmt.Sprint(err) + &quot;: &quot; + stderr.String())
	return
}

This outputs:

[awk -F &#39;\t&#39; &#39;{if ($4 == &quot;SAN FRANCISCO&quot;) print $0; }&#39; zipcodes_ca.txt]
exit status 2: awk: syntax error at source line 1
 context is
         &gt;&gt;&gt; &#39; &lt;&lt;&lt;
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 &#39;\t&#39; &#39;{if ($4 == &quot;SAN FRANCISCO&quot;) print $0; }&#39; 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.

huangapple
  • 本文由 发表于 2014年12月1日 07:50:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/27219739.html
匿名

发表评论

匿名网友

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

确定