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
+7.5k Golang : Accessing dataframe-go element by row, column and name example
+6.3k Golang : Process non-XML/JSON formatted ASCII text file example
+5.5k Golang : PGX CopyFrom to insert rows into Postgres database
+7.4k Golang : How to iterate a slice without using for loop?
+17.8k Convert JSON to CSV in Golang
+6.8k Golang : Reverse by word
+11.4k Golang : Byte format example
+7.6k Golang : Get YouTube playlist
+5.4k Golang : Generate Interleaved 2 inch by 5 inch barcode
+7.1k Nginx : Password protect a directory/folder
+9.5k Golang : Play .WAV file from command line
+7.3k Javascript : How to get JSON data from another website with JQuery or Ajax ?