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
+22.2k Golang : Read directory content with filepath.Walk()
+12.5k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+9.6k Golang : Load ASN1 encoded DSA public key PEM file example
+32.8k Golang : How to check if a date is within certain range?
+30.6k Golang : Download file example
+6.6k Golang : Experimental emojis or emoticons icons programming language
+7.2k Golang : alternative to os.Exit() function
+7.2k Golang : How to convert strange string to JSON with json.MarshalIndent
+17.6k Golang : Read data from config file and assign to variables
+10.8k Golang : How to transmit update file to client by HTTP request example
+20.2k nginx: [emerg] unknown directive "passenger_enabled"
+12.8k Python : Convert IPv6 address to decimal and back to IPv6