9

[Golang] Filename Globbing Summary

 2 years ago
source link: http://siongui.github.io/2017/04/25/go-file-name-glob-summary/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Filename Globbing Summary

April 25, 2017

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:

[6]Wildcards - GNU/Linux Command-Line Tools Summary

[7][Golang] Walk All Files in Directory


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK