Golang : Use wildcard patterns with filepath.Glob() example
Searching for files by extension can be done easily in Golang with filepath.Ext()
function. To search for files base on wildcard pattern can be done easily too with filepath.Glob()
function.
In this code example, we will use filepath.Glob()
function with a wildcard pattern to list out files with the string input
in the file names.
package main
import (
"fmt"
"path/filepath"
)
func main() {
pattern := "*input*"
matches, err := filepath.Glob(pattern)
if err != nil {
fmt.Println(err)
}
fmt.Println(matches)
// search upper directory
upperDirPattern := "../*input*"
// you can specify directly the directory you want to search as well with the pattern
// for example, /usr/files/*input*
matches, err = filepath.Glob(upperDirPattern)
if err != nil {
fmt.Println(err)
}
fmt.Println(matches)
}
Sample output:
[checkinput checkinput.go input.gif input.txt scrinputtofile scrinputtofile.go]
[../testinputfile]
Reference:
See also : Golang : Find files by extension
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.4k Golang : Read from buffered reader until specific number of bytes
+12k Golang : Check if a string contains multiple sub-strings in []string?
+4.4k Android Studio : AlertDialog to get user attention example
+4.2k Golang : When to use make or new?
+13.2k Golang : XML to JSON example
+13k Golang :Trim white spaces from a string
+4.1k Get Facebook friends working in same company
+4.1k Golang : Transform lisp or spinal case to Pascal case example
+2.9k Javascript : How to get width and height of a div?
+20.5k Golang : How to check if a connection to database is still alive ?
+9.8k Golang : unknown escape sequence error
+3.7k Unix/Linux : How to open tar.gz file ?