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 : Calculate percentage change of two values
+11.2k Golang : How to check if a string starts or ends with certain characters or words?
+11.6k Golang : Pass database connection to function called from another package and HTTP Handler
+10.4k Golang : Surveillance with web camera and OpenCV
+14k Golang : rune literal not terminated error
+9.1k Golang : How to tokenize source code with text/scanner package?
+11.7k Android Studio : Password input and reveal password example
+4.5k Golang : fmt.Println prints out empty data from struct
+7.3k Golang : How to check variable or object type during runtime?
+15.6k Golang : Get own process identifier
+11.9k Golang : List objects in AWS S3 bucket
+11.2k Golang : How to display image file or expose CSS, JS files from localhost?