Get the first directory of a path in GO
Asked Answered
O

2

14

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.

Oblige answered 9/11, 2015 at 21:53 Comment(2)
from the docs: > SplitList splits a list of paths joined by the OS-specific ListSeparator, usually found in PATH or GOPATH environment variables.Brew
ooops. that explains a lotOblige
U
21

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]
Udelle answered 9/11, 2015 at 21:58 Comment(5)
I actually wanted to avoid that due to path separator differences on windows and linux. Is there a solution in the standard library for that?Oblige
@Stefan: then use os.PathSeparator Brew
os.PathSeparator is an int so it needs to be converted.Hurling
Thanks new to go as well i didn't know iw was as simple as that to cast it to a string.Hurling
Using strings.Split will produce an empty string as the first item when used with an absolute UNIX path. Furthermore it produces two empty strings when used with specific Windows paths. Here is an example: go.dev/play/p/jlBWsVEAzlGOpus
D
4

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

Derange answered 11/7, 2021 at 22:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.