In my Go script, I’m running a shell command to get a listing of a directory and store the data. I’m using the os/exec package to run the shell command and get the output. The output is returned in a []byte. I want to be able to iterate []byte and output the elements in string format so you see the actual names of the files.
Here’s my code:
package main
import (
“log”
“os/exec”
“os”
“fmt”
“path/filepath”
“time”
“strings”
)
func main() {
var dir1 = “/dir/dir1”
files, err := exec.Command(“ls”, lspDir).Output()
if err != nil {
fmt.Println("Issue finding files: ", err)
}
files2 := string(files[:]) // converts all element of files to string
fmt.Println(files2) // this shows me all the elements in string format
for f, _ := range files2 {
fmt.Println(f) // This does not print each element in string format
}
}
Edit:files2 can be iterable but it is a string. Solution: filesArray := strings.Split(files2, "\n")
f will be the index of the filesArray and _ that you are ignoring is the actual value. Solution: for _, f := range filesArray {}
So your code should look like this in the end to achieve what you want:
package main
import (
"strings"
"fmt"
"os/exec"
)
func main() {
var dir1 = "/dir/dir1"
files, err := exec.Command("ls", lspDir).Output()
if err != nil {
fmt.Println("Issue finding files: ", err)
}
files2 := string(files[:]) // actually == it converts byte slice to string
filesArray := strings.Split(files2, "\n")
for _, f := range filesArray {
fmt.Println("shazam: ", f) // remove shazam ! this is only to demonstrate that it is iterable
}
}