Remove path from filename

Go

Go Problem Overview


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

Go Solutions


Solution 1 - Go

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

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

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

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPolinuxView Question on Stackoverflow
Solution 1 - GoAinar-GView Answer on Stackoverflow
Solution 2 - Gouser1475184View Answer on Stackoverflow
Solution 3 - GoZomboView Answer on Stackoverflow
Solution 4 - GodevinbostView Answer on Stackoverflow