Remove path from filename

后端 未结 3 937
南笙
南笙 2020-12-16 09:22

I have trivial question.

I have string which contains a filename and it\'s path. How can i remove whole path? I have tried those:

line = \"/some/pat         


        
相关标签:
3条回答
  • 2020-12-16 09:55

    If you want the base path without the fileName, you can use Dir, which is documented here: https://golang.org/pkg/path/filepath/#Dir

    Quoting part of their documentation:

    Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed.

    Also from their documentation, running this code:

    package main
    
    import (
        "fmt"
        "path/filepath"
    )
    
    func main() {
        fmt.Println("On Unix:")
        fmt.Println(filepath.Dir("/foo/bar/baz.js"))
        fmt.Println(filepath.Dir("/foo/bar/baz"))
        fmt.Println(filepath.Dir("/foo/bar/baz/"))
        fmt.Println(filepath.Dir("/dirty//path///"))
        fmt.Println(filepath.Dir("dev.txt"))
        fmt.Println(filepath.Dir("../todo.txt"))
        fmt.Println(filepath.Dir(".."))
        fmt.Println(filepath.Dir("."))
        fmt.Println(filepath.Dir("/"))
        fmt.Println(filepath.Dir(""))
    
    }
    

    will give you this output:

    On Unix: /foo/bar /foo/bar /foo/bar/baz /dirty/path . .. . . / .

    Try it yourself here:

    https://play.golang.org/p/huk3EmORFw5

    If you instead want to get the fileName without the base path, @Ainar-G has sufficiently answered that.

    0 讨论(0)
  • 2020-12-16 09:56

    The number is the index of the last slash in the string. If you want to get the file's base name, use filepath.Base:

    path := "/some/path/to/remove/file.name"
    file := filepath.Base(path)
    fmt.Println(file)
    

    Playground: http://play.golang.org/p/DzlCV-HC-r.

    0 讨论(0)
  • 2020-12-16 09:59

    You can try it in the playground!

    dir, file := filepath.Split("/some/path/to/remove/file.name")
    fmt.Println("Dir:", dir)   //Dir: /some/path/to/remove/
    fmt.Println("File:", file) //File: file.name
    
    0 讨论(0)
提交回复
热议问题