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
+9.8k Golang : Sort and reverse sort a slice of integers
+8k Golang : How To Use Panic and Recover
+4k Javascript : Empty an array example
+5.4k Clean up Visual Studio For Mac installation failed disk full problem
+19.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+11.6k How to tell if a binary(executable) file or web application is built with Golang?
+11k Golang : Roll the dice example
+6.4k Grep : How to grep for strings inside binary data
+11.2k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+51.2k Golang : Check if item is in slice/array
+37.9k Golang : Read a text file and replace certain words
+9.2k Golang : Generate EAN barcode