Created
June 25, 2022 19:34
-
-
Save jojomi/dcaabb19771167e3aa77f2f697f88251 to your computer and use it in GitHub Desktop.
Golang Filename fixer
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" | |
) | |
type RenamePlan struct { | |
BasePath string | |
From string | |
To string | |
} | |
func (x RenamePlan) String() string { | |
return fmt.Sprintf("Rename %s to %s (in %s)", x.From, x.To, x.BasePath) | |
} | |
func main() { | |
var cleanPath = os.Args[1] | |
fmt.Printf("cleaning %s...\n", cleanPath) | |
var ( | |
renames = make([]RenamePlan, 0) | |
fullPath string | |
fixedPath string | |
err error | |
) | |
f := func(path string, info os.FileInfo, err error) error { | |
fullPath = info.Name() | |
if fullPath == "Media Türkeireise" { | |
return nil | |
} | |
fixedPath, err = fixPath(fullPath) | |
if err != nil { | |
return err | |
} | |
if fixedPath != fullPath { | |
rename := RenamePlan{ | |
BasePath: filepath.Dir(path), | |
From: fullPath, | |
To: fixedPath, | |
} | |
renames = append(renames, rename) | |
fmt.Println(rename) | |
} | |
return nil | |
} | |
err = filepath.Walk(cleanPath, f) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("\n\n") | |
for _, ren := range renames { | |
fmt.Println(ren) | |
err = os.Rename(filepath.Join(ren.BasePath, ren.From), filepath.Join(ren.BasePath, ren.To)) | |
if err != nil { | |
fmt.Println(ren) | |
panic(err) | |
} | |
} | |
} | |
func fixPath(in string) (string, error) { | |
r := regexp.MustCompile(`[^- _.A-ZÄÖÜa-zäöüß0-9]+`) | |
return r.ReplaceAllString(in, "_"), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Execute as
go run filename-fixer.go "/home/jojomi/basepath"
It will go through all subfolders and subfiles of the given directory. Not much error handling and limited usability, well that's why it is a gist only and not a Github project ;).