Last active
November 9, 2018 03:31
-
-
Save pallove/b96c244fb36c8321b17c1eb085f457bc to your computer and use it in GitHub Desktop.
walk directory with filetype filter
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
package main | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
var ( | |
ext string | |
path string | |
help bool | |
) | |
func init() { | |
flag.BoolVar(&help, "h", false, "show help") | |
flag.StringVar(&path, "path", ".", "walk the directory") | |
flag.StringVar(&ext, "ext", "", "files filter in with suffix, format: \"ext1|ext2\"") | |
exec := filepath.Base(os.Args[0]) | |
flag.Usage = func() { | |
fmt.Fprintf(os.Stderr, `Usage: %s [-h help] [-path path] [-ext suffix] | |
Options: | |
`, exec) | |
flag.PrintDefaults() | |
fmt.Fprintf(os.Stderr, ` Tip: Use pipe to collect the result. | |
ex: %s > 1.txt`, exec) | |
} | |
flag.Parse() | |
if help { | |
flag.Usage() | |
os.Exit(0) | |
} | |
required := []string{} // must be checked args | |
if len(required) > 0 { | |
seen := make(map[string]bool) | |
flag.Visit(func(f *flag.Flag) { | |
seen[f.Name] = true | |
}) | |
for _, op := range required { | |
if !seen[op] { | |
flag.Usage() | |
os.Exit(1) | |
} | |
} | |
} | |
} | |
func main() { | |
ext = strings.Trim(ext, " ") | |
suffixs := strings.Split(ext, "|") | |
filepath.Walk(path, func(path string, info os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
if !info.IsDir() { | |
if ext == "" { | |
fmt.Println(path) | |
} else { | |
for _, suffix := range suffixs { | |
// if flag, _ := regexp.MatchString("^\\.\\w+$", suffix); flag { | |
if strings.HasSuffix(path, "."+suffix) { | |
fmt.Println(path) | |
break | |
} | |
// } | |
} | |
} | |
} | |
return nil | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment