Golang : Find files by name - cross platform example
Problem:
You want to find or locate files by name or by wildcard in your Golang program to do stuff like renaming files or archiving log files. You also want the solution to be cross platform and want the search facility to be available without "shelling out" or "os.Exec" to use specific operating system find
program. How to do that?
Solution:
Use filepath.Glob()
function to search for files by name in a given target directory and handle wildcard *
search.
Here you go!
package main
import (
"fmt"
"os"
"path/filepath"
)
func findFile(targetDir string, pattern []string) {
for _, v := range pattern {
matches, err := filepath.Glob(targetDir + v)
if err != nil {
fmt.Println(err)
}
if len(matches) != 0 {
fmt.Println("Found : ", matches)
}
}
}
func main() {
if len(os.Args) <= 2 {
fmt.Printf("USAGE : %s <target_directory> <target_filename or part of filename> \n", os.Args[0])
os.Exit(0)
}
targetDirectory := os.Args[1] // get the target directory
fileName := os.Args[2:] // to handle wildcard such as filename*.go
findFile(targetDirectory, fileName)
}
Sample output:
./findfilebyname2 ../ find*
will return nothing, because no file the starts with find
is found on upper directory.
./findfilebyname2 ./ find*
Found : [./findallindex.go]
Found : [./findbiggest.go]
Found : [./findduplicate]
Found : [./findduplicate.go]
Found : [./findfilebyname.go]
Found : [./findfilebyname2]
Found : [./findfilebyname2.go]
Found : [./findsmallest.go]
just searching for a single file in target directory
./findfilebyname2 /Users/admin/ findsmallest.go
Found : [/Users/admin/findsmallest.go]
NOTE: If you are looking to search from a given target directory and traverse down the directory hierarchy, you will need to use filepath.Walk()
to do that. See example at https://www.socketloop.com/tutorials/golang-find-file-size-disk-usage-with-filepath-walk
References:
https://www.socketloop.com/tutorials/golang-how-to-check-if-slice-or-array-is-empty
https://www.socketloop.com/tutorials/golang-use-wildcard-patterns-with-filepath-glob-example
https://www.socketloop.com/tutorials/golang-find-duplicate-files-with-filepath-walk
See also : Golang : Find file size(disk usage) with filepath.Walk
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
+19.4k Golang : Reset or rewind io.Reader or io.Writer
+18.5k Golang : Populate dropdown with html/template example
+31.6k Golang : Copy directory - including sub-directories and files
+5.2k Unix/Linux : How to find out the hard disk size?
+13.6k Golang : syscall.Socket example
+5k Golang : Intercept, inject and replay HTTP traffics from web server
+20.1k Golang : Underscore or snake_case to camel case example
+11.2k SSL : The certificate is not trusted because no issuer chain was provided
+45.5k Golang : Marshal and unmarshal json.RawMessage struct example
+4.2k Linux : sudo yum updates not working
+28.8k Golang : JQuery AJAX post data to server and send data back to client example
+22.4k Golang : Gorilla mux routing example