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.
For finding a specific file type, simply use the 'type:' command, followed by the file extension. For example, you can find . docx files by searching 'type: . docx'.
You can check the file extension from the Type column in Windows file explorer. Alternatively, you could right-click on the file and select Properties. You'll see the Type of file in the General tab of file properties. If it says File, you know that the file has no extension.
In the Go programming language, to get the file name extension used by the given path – we use the Ext() function of path/filepath package. The Ext() function returns the file name extension used by the given path.
Starting with Go 1.16 (Feb 2021), you can use filepath.WalkDir
for better
performance:
package main
import (
"io/fs"
"path/filepath"
)
func find(root, ext string) []string {
var a []string
filepath.WalkDir(root, func(s string, d fs.DirEntry, e error) error {
if e != nil { return e }
if filepath.Ext(d.Name()) == ext {
a = append(a, s)
}
return nil
})
return a
}
func main() {
for _, s := range find("/root", ".md") {
println(s)
}
}
https://golang.org/pkg/path/filepath#WalkDir
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With