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
+34.8k Golang : Strip slashes from string example
+4.4k Facebook : How to place save to Facebook button on your website
+5.8k Golang : Get missing location after unmarshal binary and gob decode time.
+6.1k Grep : How to grep for strings inside binary data
+11.8k Golang : md5 hash of a string
+9.5k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+4.4k Linux/MacOSX : How to symlink a file?
+18.9k Golang : Delete item from slice based on index/key position
+45.4k Golang : Read tab delimited file with encoding/csv package
+17.5k Golang : How to log each HTTP request to your web server?
+5.1k Golang : What is StructTag and how to get StructTag's value?
+14.2k Golang : Rename directory