Skip to content

Instantly share code, notes, and snippets.

@barisvelioglu
Forked from jlinoff/walker.go
Created October 25, 2021 09:49
Show Gist options
  • Save barisvelioglu/631763aeb8c57740b9b868b1d2f58427 to your computer and use it in GitHub Desktop.
Save barisvelioglu/631763aeb8c57740b9b868b1d2f58427 to your computer and use it in GitHub Desktop.
go example that shows how to walk a directory using a regular expression filter and collect files that match
// This example demonstrates how to use go to walk a directory
// and filter the contents by using filepath.Walk with
// variables in the external scope to provide the filter and
// to capture the file names.
//
// To build:
// go build walk.go
// Usage:
// walk <pattern> <files>
//
// License:
// MIT Open Source
// Copyright (c) 2016 by Joe Linoff
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
)
func main() {
if len(os.Args) > 1 {
re := regexp.MustCompile(os.Args[1]);
for i := 2 ; i < len(os.Args); i++ {
filteredSearchOfDirectoryTree(re, os.Args[i])
}
}
}
// filteredSearchOfDirectoryTree Walks down a directory tree looking for
// files that match the pattern: re. If a file is found print it out and
// add it to the files list for later user.
func filteredSearchOfDirectoryTree(re *regexp.Regexp, dir string) error {
// Just a demo, this is how we capture the files that match
// the pattern.
files := []string{}
// Function variable that can be used to filter
// files based on the pattern.
// Note that it uses re internally to filter.
// Also note that it populates the files variable with
// the files that matches the pattern.
walk := func(fn string, fi os.FileInfo, err error) error {
if re.MatchString(fn) == false {
return nil
}
if fi.IsDir() {
fmt.Println(fn + string(os.PathSeparator))
} else {
fmt.Println(fn)
files = append(files, fn)
}
return nil
}
filepath.Walk(dir, walk)
fmt.Printf("Found %[1]d files.\n", len(files))
return nil
}
@barisvelioglu
Copy link
Author

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment