Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use double star glob in Go?

Tags:

go

glob

It seems like Go is one of few languages that does not seem to understand the double star ("globstar") syntax for file globbing. At least this does not seems to work as expected:

filepath.Glob(dir + "/**/*.bundle/*.txt")

Am I missing something about the filepath implementation? Is there a library around that does support this?

like image 758
tcurdt Avatar asked Nov 07 '14 20:11

tcurdt


2 Answers

The filepath.Glob implementation uses filepath.Match under the hood. Turns out the specs for that do not cover the quite common (.gitignore, zsh) double star pattern. By no means the same - but for my use case I managed to work around it with this little function:

func glob(dir string, ext string) ([]string, error) {

  files := []string{}
  err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
    if filepath.Ext(path) == ext {
      files = append(files, path)
    }
    return nil
  })

  return files, err
}

I am still open for a better implementation with proper double star matching.

like image 53
tcurdt Avatar answered Oct 20 '22 19:10

tcurdt


I've written a small extension library that supports double star globbling. With this directory structure:

$ find a
a
a/b
a/b/c.d
a/b/c.d/e.f

You can use a/**/*.* to match everything under the a directory that contains a dot, like so:

package main

import (
  "fmt"

  "github.com/yargevad/filepathx"
)

func main() {
  matches, err := filepathx.Glob("./a/**/*.*")
  if err != nil {
    panic(err)
  }

  for _, match := range matches {
    fmt.Printf("MATCH: [%v]\n", match)
  }
}

Which outputs:

$ go run example.go
MATCH: [a/b/c.d]
MATCH: [a/b/c.d/e.f]
like image 35
Dave Gray Avatar answered Oct 20 '22 17:10

Dave Gray