Stefan
Stefan

Reputation: 2194

Get the first directory of a path in GO

In Go, is it possible to get the root directory of a path so that

foo/bar/file.txt

returns foo? I know about path/filepath, but

package main

import (
        "fmt"
        "path/filepath"
)

func main() {
        parts := filepath.SplitList("foo/bar/file.txt")
        fmt.Println(parts[0])
        fmt.Println(len(parts))
}

prints foo/bar/file.txt and 1 whereas I would have expected foo and 3.

Upvotes: 14

Views: 16070

Answers (2)

Zombo
Zombo

Reputation: 1

Note that if you just need the first part, strings.SplitN is at least 10 times faster from my testing:

package main
import "strings"

func main() {
   parts := strings.SplitN("foo/bar/file.txt", "/", 2)
   println(parts[0] == "foo")
}

https://golang.org/pkg/strings#SplitN

Upvotes: 4

icza
icza

Reputation: 417987

Simply use strings.Split():

s := "foo/bar/file.txt"
parts := strings.Split(s, "/")
fmt.Println(parts[0], len(parts))
fmt.Println(parts)

Output (try it on the Go Playground):

foo 3
[foo bar file.txt]

Note:

If you want to split by the path separator of the current OS, use os.PathSeparator as the separator:

parts := strings.Split(s, string(os.PathSeparator))

filepath.SplitList() splits multiple joined paths into separate paths. It does not split one path into folders and file. For example:

fmt.Println("On Unix:", filepath.SplitList("/a/b/c:/usr/bin"))

Outputs:

On Unix: [/a/b/c /usr/bin]

Upvotes: 20

Related Questions