怎样调用像cat filename|grep "aaa"之类的命令

我想实现的这样的一个命令:

cat filename|grep "aaa"

用os.Command好像不能实现

共 2 个回复


polaris

试试将“/bin/bash”作为命令,cat filename|grep "aaa"作为参数

# 0

jimmykuu

io.Pipe,下面代码供参考:

package main

import (
    "bytes"
    "fmt"
    "io"
    "os/exec"
)

func main() {
    cmd1 := exec.Command("cat", "command.go")
    cmd2 := exec.Command("grep", "fmt")

    r, w := io.Pipe()
    cmd1.Stdout = w
    cmd2.Stdin = r

    var out bytes.Buffer
    cmd2.Stdout = &out

    cmd1.Start()
    cmd2.Start()
    cmd1.Wait()
    w.Close()
    cmd2.Wait()

    fmt.Println(out.String())
}
# 1