duangan4070
duangan4070
2018-03-06 22:48

exec.Command如何中断对sed的调用?

已采纳

I'm trying to run the following command from go.

sed -i 's|/home/output||g' /tmp/results.json

Which blats out /home/output from the file /tmp/result.json.

If I run this from a terminal it works perfectly. However, I can't figure out why it's not liking being run from go exec.

Here is my code.

package main

import (
        "fmt"
        "log"
        "os"
        "os/exec"
)

func main() {
        cmd := exec.Command("sed", "-i", "'s|/octane/data||g'", "./results.json")
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr

        if err := cmd.Start(); err != nil {
                log.Fatal(err)
        }

        if err := cmd.Wait(); err != nil {
                log.Fatal(err)
        }
}

The specific error is:

sed: -e expression #1, char 1: unknown command: `''
2018/03/07 11:48:01 exit status 1

What is causing this unexpected behavior?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duandai3964 duandai3964 3年前

    Try this :

    cmd := exec.Command("sed", "-i", "s|/octane/data||g", "./results.json")
    

    wrong quoting issue.

    The single quotes are necessary for shell but not for the exec.Command call.

    点赞 评论 复制链接分享

相关推荐