LoginSignup
14
3

More than 5 years have passed since last update.

Go言語でパス情報から拡張子なしのファイル名を取り出したい

Last updated at Posted at 2017-08-15

パス情報から拡張子を除去したファイル名を取り出したい!
具体的に言うと以下のようなケースです。

/path/to/file.name.hoge.name から file.name.hoge だけ抜き出したい

こういう場面に遭遇したのですが、ピタリとはまる例を見つけられなかったので書いてみました٩( 'ω' )و

※ mattnさんにコメントでいただいた処理で修正しました!

GetFileNameWithoutExt.go
package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    paths := []string{
        filepath.Join("path", "to", "file.name.hoge.name"),
        filepath.Join("path", "to", "file.name"),
        filepath.Join("path", "to", "file"),
    }

    for _, path := range paths {
        filename := getFileNameWithoutExt(path)
        fmt.Printf("%s -> %s\n", path, filename)
    }
}

func getFileNameWithoutExt(path string) string {
    // Fixed with a nice method given by mattn-san
    return filepath.Base(path[:len(path)-len(filepath.Ext(path))])
}

実行結果は以下のようになります。

$ go run GetFileNameWithoutExt.go
path\to\file.name.hoge.name -> file.name.hoge
path\to\file.name -> file
path\to\file -> file

やっぱりGo言語って面白いですね。

簡単に始められてパワフル、そして奥が深い。。
学び始めてそろそろ1年が経ちそうですが、初心に返ってバイブル片手に修行し直しています。
もっと頑張るぉ~٩( 'ω' )و

プログラミング言語Go (ADDISON-WESLEY PROFESSIONAL COMPUTING SERIES)

14
3
2

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
14
3