-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
83 lines (70 loc) · 1.81 KB
/
main.go
File metadata and controls
83 lines (70 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"flag"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"regexp"
)
var dir_flag = flag.String("dir", "", "the directory for the files to be renamed")
var pat_flag = flag.String("pattern", "", "the regex for the target files ( single quoted )")
func processTargetDir(dir string) (string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", nil
}
if dir == "" {
return cwd, nil
}
if filepath.IsAbs(dir) {
return dir, nil
} else {
return filepath.Join(cwd, dir), nil
}
}
// ========= The logic for renaming files. Customize as needed. =============
func NewFileName(origFileName string) string {
pattern := `(.+)_(\d\d\d)\.txt`
re := regexp.MustCompile(pattern)
matches := re.FindStringSubmatch(origFileName)
part1, part2 := matches[1], matches[2]
return fmt.Sprintf("%s - %s.txt", part2, part1)
}
// ==========================================================================
func main() {
flag.Parse()
dir := *dir_flag
targetPattern := *pat_flag
targetDir, err := processTargetDir(dir)
if err != nil {
log.Fatalf("Processing targetDir failed: %s", err)
}
var walkFn fs.WalkDirFunc
walkFn = func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
origFileName := d.Name()
matched, e := regexp.MatchString(targetPattern, origFileName)
if e != nil || !matched {
return nil
}
newFileName := NewFileName(origFileName)
newPath := filepath.Join(filepath.Dir(path), newFileName)
if err := os.Rename(path, newPath); err != nil {
log.Printf("Failed to rename %s\n", path)
return nil // continue walking to other paths
}
fmt.Printf("Renamed %s to %s\n", path, newPath)
return nil
}
err = filepath.WalkDir(targetDir, walkFn)
if err != nil {
log.Fatalf("error walking file tree: %s", err)
}
}