How to convert byte slice elements into strings


(Mo) #1

Hi,

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
	}
}

(Ashish Shekar) #2

The 2 mistakes that I can spot is that:

  1. Edit: files2 can be iterable but it is a string.
    Solution: filesArray := strings.Split(files2, "\n")

  2. 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
	}
}

Let me know if I missed anything.


(Mo) #3

@codekid, thank you that worked. :slightly_smiling_face:

I totally missed that I reversed the _, f by mistake. And now also realize that I need the filesArray as you put it.


(Ashish Shekar) #4

Ya, I used to interchange it all the time. I made a habit to ignore index by default and then use it if I need it.

Glad that it worked :smile:


(system) closed #5

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.