2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Go lang でファイルパスの最後のみ取得する

Posted at

Go lang で、ファイルパスの最後のみを返すメソッドないかなと思って調査した。filepath.Base がそれで、パスの最後の要素を返す関数。

// Base returns the last element of path.
// Trailing path separators are removed before extracting the last element.
// If the path is empty, Base returns ".".
// If the path consists entirely of separators, Base returns a single separator.
func Base(path string) string {

良さげだが、両方のパスで動作するか確かめてみる。Windows の環境で、Windows ベースのファイル区切り文字と、Linuxベースの両方を試してみる。

Linux ベース on Windows

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	path := "/some/path/to/foo.txt"
	file := filepath.Base(path)
	fmt.Println(file)
}

実行結果

$ go run main.go
foo.txt

Windows ベース on Windows

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	path := "C:\\Users\\tsushi\\Downloads\\stress-testing\\terraform"
	file := filepath.Base(path)
	fmt.Println(file)
}

実行結果

$ go run main.go
terraform

どちらでも無事動きそう。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?