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
+30.8k Golang : bufio.NewReader.ReadLine to read file line by line
+13.9k Golang : How to convert a number to words
+10.9k Golang : How to pipe input data to executing child process?
+22k Golang : Read directory content with filepath.Walk()
+5.7k AWS S3 : Prevent Hotlinking policy
+10.2k Golang : Resolve domain name to IP4 and IP6 addresses.
+10k Golang : Embed secret text string into binary(executable) file
+14.3k Golang : Rename directory
+15.7k Golang : Generate universally unique identifier(UUID) example
+5.2k Golang : fmt.Println prints out empty data from struct
+12.3k Golang : Remove or trim extra comma from CSV
+9.1k Golang : Terminate-stay-resident or daemonize your program?