Remove path from filename

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/path/to/remove/file.name"
line := strings.LastIndex(line, "/")
fmt.Println(line)

It prints some strange number:

38

I need it without last slash

Thanks a lot


Solution 1:

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.

Solution 2:

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

Solution 3:

Another option:

package main
import "path"

func main() {
   line := "/some/path/to/remove/file.name"
   line = path.Base(line)
   println(line == "file.name")
}

https://golang.org/pkg/path#Base

Solution 4:

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.