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
+11.8k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+8.3k Golang : Convert word to its plural form example
+13.4k Golang : How to get year, month and day?
+9.4k Golang : Extract or copy items from map based on value
+10.4k Generate Random number with math/rand in Go
+22.8k Golang : Gorilla mux routing example
+17.4k Golang : Find smallest number in array
+11.4k Golang : Generate DSA private, public key and PEM files example
+17.9k Golang : Get all upper case or lower case characters from string example
+7.3k Golang : Accessing dataframe-go element by row, column and name example
+25.3k Golang : Generate MD5 checksum of a file
+11.5k Get form post value in Go