Select Files With Glob Patterns

Match file names against shell-style patterns with filepath.Glob and fs.Glob, getting sorted results and an empty slice rather than an error on no match.

GoCli Tooling

Code

gosnippet
56 lines
package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
)

func main() {
	root, err := os.MkdirTemp("", "glob-*")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(root)

	for _, name := range []string{"a.log", "b.log", "c.txt", "sub/d.log"} {
		full := filepath.Join(root, name)
		if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
			fmt.Println(err)
			return
		}
		if err := os.WriteFile(full, []byte("x"), 0o644); err != nil {
			fmt.Println(err)
			return
		}
	}

	// filepath.Glob returns the matching files, sorted by name
	matches, err := filepath.Glob(filepath.Join(root, "*.log"))
	if err != nil {
		fmt.Println("glob:", err)
		return
	}
	fmt.Println("*.log:")
	for _, m := range matches {
		fmt.Println("  ", filepath.Base(m))
	}

	// fs.Glob works on any fs.FS, with patterns in relative paths
	sub, err := fs.Glob(os.DirFS(root), "sub/*.log")
	if err != nil {
		fmt.Println("fs glob:", err)
		return
	}
	fmt.Println("sub/*.log:", sub)

	// a miss returns an empty slice, not an error
	none, err := filepath.Glob(filepath.Join(root, "*.zip"))
	if err != nil {
		fmt.Println("glob:", err)
		return
	}
	fmt.Println("*.zip matches:", len(none))
}

How the snippet works

Select Files With Glob Patterns reduces to the function main.

The one repetition in this snippet is the loop for _, name := range []string{"a.log", "b.log", "c.txt", "sub/d.log"}. Error handling is inline: 6 places test err != nil and branch immediately. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.

Applying it

Running the file prints labeled results such as glob:, *.log:, fs glob: — each operation’s effect is visible in the output.

Statements that carry the weight

for _, name := range []string{"a.log", "b.log", "c.txt", "sub/d.log"} {
	full := filepath.Join(root, name)
	if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
		fmt.Println(err)
		return
	}
	if err := os.WriteFile(full, []byte("x"), 0o644); err != nil {
		fmt.Println(err)
		return
	}
}
for _, m := range matches {
	fmt.Println("  ", filepath.Base(m))
}
if err != nil {
	fmt.Println(err)
	return
}

Interactive Tools for This Topic

FAQ

What does Select Files With Glob Patterns print when run?
Running the file directly is enough — expect labeled output lines such as `glob:`, `*.log:`, `fs glob:`.