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
+33.5k Golang : Upload and download file to/from AWS S3
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+30.1k Golang : Math pow(the power of x^y) example
+9.1k Golang : How to tokenize source code with text/scanner package?
+11.5k Golang : Get terminal width and height example
+26.8k Golang : Read, Write(Create) and Delete Cookie example
+29.8k Golang : Convert an image file to []byte
+12.7k Golang : How to convert a number to words
+19.8k Golang : Sort and reverse sort a slice of strings
+9.1k Golang : cannot assign type int to value (type uint8) in range error
+8k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+24.2k Golang : How to read integer value from standard input ?