Filepath Base Dir Ext Decomposition

Split file paths into directory, base name, and extension with filepath.Dir, filepath.Base, and filepath.Ext so CLI tools can name outputs predictably.

GoCli Tooling

Code

gosnippet
23 lines
package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	for _, path := range []string{
		"/etc/nginx/nginx.conf",
		"reports/2026/q4.csv",
		"Makefile",
		"archive.tar.gz",
	} {
		fmt.Printf("%s -> base=%q dir=%q ext=%q\n",
			path, filepath.Base(path), filepath.Dir(path), filepath.Ext(path))
	}

	// Base + Dir 重组回原路径
	joined := filepath.Join(filepath.Dir("/etc/nginx/nginx.conf"),
		filepath.Base("/etc/nginx/nginx.conf"))
	fmt.Println("rejoined:", joined)
}

Splitting a path into parts

All of the logic lives in the function main.

The loop for _, path := range []string is the only repeated construct.

Caveats

  • Nothing to install: the snippet stays inside the standard library.

Applying it

The main signature reads func main()

The run emits 1 labeled section — rejoined: — one per step.

Statements that matter

for _, path := range []string{
	"/etc/nginx/nginx.conf",
	"reports/2026/q4.csv",
	"Makefile",
	"archive.tar.gz",
} {
	fmt.Printf("%s -> base=%q dir=%q ext=%q\n",
		path, filepath.Base(path), filepath.Dir(path), filepath.Ext(path))
}

Interactive Tools for This Topic

FAQ

What does Filepath Base Dir Ext Decomposition print when run?
Run it as a complete program — the output lines carry labels such as `rejoined:`.