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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.