Created
March 15, 2020 01:37
-
-
Save yujp/8db8ca94d43fb7b0f7655df1459561c6 to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"os" | |
"path/filepath" | |
"regexp" | |
"flag" | |
) | |
type mode int | |
const ( | |
modePrint mode = iota | |
modeMove | |
) | |
func main() { | |
dir := flag.String("dir", ".", "directory path") | |
name := flag.String("name", "^.+$", "pattern of file name") | |
dest := flag.String("dest", "", "destination path") | |
mode := flag.String("mode", "print", "move or print") | |
exclude := flag.String("exclude", "$^", "exclude pattern of file name") | |
flag.Parse() | |
nameRe := regexp.MustCompile(*name) | |
excludeRe := regexp.MustCompile(*exclude) | |
modeNo := modeMove | |
if *mode == "print" { | |
modeNo = modePrint | |
} | |
err := filepath.Walk(*dir, func(path string, info os.FileInfo, err error) error { | |
if err != nil { | |
return err | |
} | |
if info.IsDir() { | |
return nil //filepath.SkipDir | |
} | |
bn := filepath.Base(path) | |
if !nameRe.MatchString(bn) { | |
return nil | |
} | |
if excludeRe.MatchString(bn) { | |
return nil | |
} | |
bn2 := nameRe.ReplaceAllString(bn, *dest) | |
if bn == bn2 { | |
return nil | |
} | |
switch modeNo { | |
case modePrint: | |
fmt.Printf("%s\t%s\n", bn, bn2) | |
case modeMove: | |
d := filepath.Dir(bn2) | |
os.MkdirAll(d, 0755) | |
if err := os.Rename(path, bn2); err != nil { | |
return err | |
} | |
} | |
return nil | |
}) | |
if err != nil { | |
fmt.Printf("error walking the path %q: %v\n", *dir, err) | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment