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
+28.9k Golang : Get first few and last few characters from string
+12.5k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+20k Golang : Convert seconds to human readable time format example
+6.1k Golang : How to get capacity of a slice or array?
+14.3k Golang : How to check if your program is running in a terminal
+8.1k Golang : Metaprogramming example of wrapping a function
+11.6k Golang : GTK Input dialog box examples
+17.2k Golang : Check if IP address is version 4 or 6
+8k Golang : Routes multiplexer routing example with regular expression control
+9.5k Golang : Quadratic example
+9.1k Android Studio : Indicate progression with ProgressBar example
+6k Golang : How to write backslash in string?