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
+50.9k Golang : How to get struct field and value by name
+10.9k Golang : Find and draw contours with OpenCV example
+14.4k Golang : How to add color to string?
+4k Facebook : How to place save to Facebook button on your website
+11.7k Golang : Exit, terminating or aborting a program
+11.3k Golang : convert(cast) string to integer value
+21.8k Golang : Test file read write permission example
+9.8k Golang : Bubble sort example
+9.1k Golang : Test a slice of integers for odd and even numbers
+12.2k Golang : List objects in AWS S3 bucket
+6.7k Golang : Example of how to detect which type of script a word belongs to
+24.1k Golang : Storing cookies in http.CookieJar example