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
+4.3k Golang : How to deal with configuration data?
+3.7k Linux : sudo yum updates not working
+16.7k Golang : Convert IPv4 address to decimal number(base 10) or integer
+4.1k Golang : micron to centimeter example
+6.3k Golang : Dealing with struct's private part
+28.1k Golang : Get time.Duration in year, month, week or day
+5k Java : Human readable password generator
+44.3k Golang : Marshal and unmarshal json.RawMessage struct example
+16.8k Golang : Display list of time zones with GMT
+6.8k Android Studio : Rating bar example
+10.7k Golang : md5 hash of a string