markwallsgrove

Golang - Find file names in tree with regex using walk

May 8th, 2015
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.82 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "flag"
  5.     "fmt"
  6.     "os"
  7.     "path/filepath"
  8.     "regexp"
  9. )
  10.  
  11. type blah struct {
  12.     found   []string
  13.     pattern regexp.Regexp
  14. }
  15.  
  16. func (b *blah) visit(path string, f os.FileInfo, err error) error {
  17.     if b.pattern.MatchString(f.Name()) {
  18.         b.found = append(b.found, f.Name())
  19.     }  
  20.  
  21.     return nil
  22. }
  23.  
  24. func createBlah(pattern *regexp.Regexp) blah {
  25.     b := blah{}
  26.     b.found = []string{}
  27.     b.pattern = *pattern
  28.     return b
  29. }
  30.  
  31. func main() {
  32.     flag.Parse()
  33.     pattern := flag.Arg(0)
  34.     root := flag.Arg(1)
  35.  
  36.     fmt.Println("compile", pattern)
  37.     regxPattern, err := regexp.Compile(pattern)
  38.     if err != nil {
  39.         panic(err)
  40.     }  
  41.  
  42.     b := createBlah(regxPattern)
  43.     filepath.Walk(root, b.visit)
  44.     fmt.Println("Found paths:", b.found)
  45. }
Advertisement
Add Comment
Please, Sign In to add comment