Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang command not working even though manually executing it does

Tags:

go

awk

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.

like image 888
Elliot Larson Avatar asked Nov 23 '25 01:11

Elliot Larson


1 Answers

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.

like image 176
Alex Gitelman Avatar answered Nov 27 '25 12:11

Alex Gitelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!