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
+4.7k Swift : Get substring with rangeOfString() function example
+12.1k Golang : reCAPTCHA example
+19.6k Golang : How to read float value from standard input ?
+13.3k Golang : How to filter a map's elements for faster lookup
+27.7k Golang : How to create new XML file ?
+14.2k Golang : Get current time from the Internet time server(ntp) example
+3.7k JavaScript : Rounding number to decimal formats to display currency
+4.4k Golang : Detect words using using consecutive letters in a given string
+20.7k Golang : How to run Golang application such as web server in the background or as daemon?
+6.4k Golang : Lock executable to a specific machine with unique hash of the machine
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+6k Golang : Squaring elements in array