[Golang] Filename Globbing Summary


Filename globbing are found in several places in Go standard library.

I want to how the it works, so I use a small example to test. I have the two txt files as follows:

testdir/a.txt
textdir/subdir/b.txt

Use testdir/*.txt as pattern in filepath.Glob:

package main

import (
      "path/filepath"
      "fmt"
)

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

      fmt.Println(matches)
}

The output:

[testdir/a.txt]

As expected, * does not match sub-directory. How about **? Modify the pattern from testdir/*.txt to testdir/**.txt, and the output is:

[testdir/a.txt]

The output is the same. ** does not match zero or more directories [3].

If sub-directory depth is known, we can still match file in sub-directory. For example, modify the pattern from testdir/*.txt to testdir/*/*.txt [4]. The output is:

[testdir/subdir/b.txt]

The file in sub-directory is matched.


My summary

  • * does not match sub-directories.
  • ** is not supported, i.e., does not match zero or more directories.
  • If depth of sub-directories is known, sub-directories can be matched with workaround.
  • There are third-party packages which provides more complete glob features [5].

Tested on:

  • Ubuntu Linux 17.04
  • Go 1.8.1

References:

[1]
[2]
[3]path/filepath: Glob should support `**` for zero or more directories · Issue #11862 · golang/go · GitHub
[4]filebeat wildcard for directories · Issue #2084 · elastic/beats · GitHub
[5]
[6]Wildcards - GNU/Linux Command-Line Tools Summary
[7][Golang] Walk All Files in Directory
[8]