Search code examples
goglob

How to use double star glob in Go?


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?


Solution

  • 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.