递归查找目录中的文件

递归查找目录中的文件

问题描述:

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.

我想递归地在目录中找到所有与特定模式匹配的文件(包括子目录)。 我写了代码来做到这一点: p>

  libRegEx,e:= regexp.Compile(“ ^。+ \\。(dylib)$”)
if e!= nil  {
 log.Fatal(e)
} 
 
files,err:= ioutil.ReadDir(“ / usr / lib”)
if err!= nil {
 log.Fatal(err)
} \  n 
对于_,f:=范围文件{
如果libRegEx.MatchString(f.Name()){
 println(f.Name())
} 
} 
  code>  pre  > 
 
 

不幸的是,它仅在 / usr / bin code>中搜索,但我也想在其子目录中搜索匹配项。 我该如何实现? 谢谢。 p> div>

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(f.Name())
    }
    return nil
})
if e != nil {
    log.Fatal(e)
}