Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go find files in directory recursively

I want to find all files matching a specific pattern in a directory recursively (including subdirectories). I wrote the code to do this:

libRegEx, e := regexp.Compile("^.+\\.(dylib)$")
if e != nil {
    log.Fatal(e)
}

files, err := ioutil.ReadDir("/usr/lib")
if err != nil {
    log.Fatal(err)
}

for _, f := range files {
    if libRegEx.MatchString(f.Name()) {
        println(f.Name())
    }
}

Unfortunately, it only searches in /usr/bin, but I also want to search for matches in its subdirectories. How can I achieve this? Thanks.

like image 446
Netherwire Avatar asked Nov 13 '17 14:11

Netherwire


Video Answer


2 Answers

Starting with Go 1.16 (Feb 2021), you can use filepath.WalkDir:

package main

import (
   "io/fs"
   "path/filepath"
)

func walk(s string, d fs.DirEntry, err error) error {
   if err != nil {
      return err
   }
   if ! d.IsDir() {
      println(s)
   }
   return nil
}

func main() {
   filepath.WalkDir("..", walk)
}
like image 79
Zombo Avatar answered Oct 17 '22 07:10

Zombo


The standard library's filepath package includes Walk for exactly this purpose: "Walk walks the file tree rooted at root, calling walkFn for each file or directory in the tree, including root." For example:

libRegEx, e := regexp.Compile("^.+\\.(dylib)$")
if e != nil {
    log.Fatal(e)
}

e = filepath.Walk("/usr/lib", func(path string, info os.FileInfo, err error) error {
    if err == nil && libRegEx.MatchString(info.Name()) {
        println(info.Name())
    }
    return nil
})
if e != nil {
    log.Fatal(e)
}
like image 20
Adrian Avatar answered Oct 17 '22 08:10

Adrian