Search code examples
arraysfilegofile-ioglob

How do I find all files that have a certain extension in Go, regardless of depth?


I have a directory structure that looks like this:

/root
  /folder_1
    file_name_1.md
  /folder_2
    file_name_2.md
  /folder_3
    file_name_3.md
  /folder_4
    /sub_folder_1
      file_name_4_1.md
    file_name_4.md

Is there a glob function that I could use to get an array containing the file path of the .md files?

For example:

[
  "/root/folder_1/file_name_1.md",
  "/root/folder_2/file_name_2.md",
  "/root/folder_3/file_name_3.md",
  "/root/folder_4/sub_folder_1/file_name_4_1.md",
  "/root/folder_4/file_name_4.md"
]

Thanks.


Solution

  • The function below will recursively walk through a directory and return the paths to all files whose name matches the given pattern:

    func WalkMatch(root, pattern string) ([]string, error) {
        var matches []string
        err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
            if err != nil {
                return err
            }
            if info.IsDir() {
                return nil
            }
            if matched, err := filepath.Match(pattern, filepath.Base(path)); err != nil {
                return err
            } else if matched {
                matches = append(matches, path)
            }
            return nil
        })
        if err != nil {
            return nil, err
        }
        return matches, nil
    }
    

    Usage:

    files, err := WalkMatch("/root/", "*.md")