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
+15.3k Golang : Gzip file example
+5.2k Golang : Extract sub-strings
+32.6k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+11.2k Golang : Covert map/slice/array to JSON or XML format
+6.4k Golang : What fmt.Println() can do and println() cannot do
+40.1k Golang : Convert string to array/slice
+29.4k Golang : Get local IP and MAC address
+8.6k Golang : Load ASN1 encoded DSA public key PEM file example
+18.4k Golang : Append content to a file
+4.7k Unix/Linux : How to test user agents blocked successfully ?
+37.7k Golang : How to iterate over a []string(array)
+26.6k Golang : Read, Write(Create) and Delete Cookie example