Home > database >  How can I turn bash exec.Command returns into Arrays?
How can I turn bash exec.Command returns into Arrays?

Time:02-24

I'm trying to find files that end in hello.go

statement:= "find "CurrentDirectory" -print | grep -i hello.go"
result, error := exec.Command("bash", "-c", statement).Output()

This gives me a list containing 2 file paths and I try to turn them into arrays that I can individually address using:

Directory_array := strings.Split(string(result),"\n")

fmt.Println(len(Directory_array) )

The length of the array shows as "3" but the array is empty except for the 0th position.

Independently the code lines work but not together. How can I get the array to fill with individual paths?

CodePudding user response:

In your case, use strings.FieldsFunc instead of strings.Split. For example:

statement:= "find . -print | grep -i hello"
result, err := exec.Command("bash", "-c", statement).Output()
if err != nil {
    panic(err)
}

ds := strings.FieldsFunc(string(result), func(r rune) bool {
    return r == '\n'
})
for i, d := range ds {
    fmt.Println(i, d)
}

Further reading:

  1. strings.FieldsFunc - go.dev
  2. strings.FieldsFunc vs strings.Split - Medium

CodePudding user response:

You could use the stdout pipe and read line by line using a Scanner.

func main() {
    cmd := exec.Command("ls", "-l")
    out, _ := cmd.StdoutPipe()
    s := bufio.NewScanner(out)

    cmd.Start()
    defer cmd.Wait()

    for s.Scan() {
        fmt.Println("new line:")
        fmt.Println(s.Text())
    }
}

If you want to store this into a slice, you can create the slice beforehand and append to it.

lines := make([]string, 0, 10)
for s.Scan() { lines = append(lines, s.Text()) }

CodePudding user response:

You have missed calling Run() in your code. Here is how to fix it:

statement:= "find "CurrentDirectory" -print | grep -i hello.go"
cmd := exec.Command("bash", "-c", statement)
err := cmd.Run()
if err != nil {
    ...
}
result, error := cmd.Output()

P.S. Why not to use os.Walk()?

  •  Tags:  
  • go
  • Related