Created
September 26, 2016 16:20
-
-
Save jlinoff/1c44eabd5a19c23a3e0755d6207891db 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment