// vim: set sw=8 ts=8 si et: // Written by Guido Socher // License: Totally free. No warranty are guarantees at all. Do with it what you want. // Compile this with the commands: // go build renclean.go // strip renclean // package main import "os" import "fmt" import "regexp" import "strings" func help() { fmt.Println("Clean file names from non unix friendly characters") fmt.Print(`USAGE: renclean [-h][-f] file [file2] .... OPTIONS: -h this help -f force rename all files and directories not just regular files EXAMPLE: renclean * This will fix the file names of all files in the current directory. Version: 2016-04-06 `) os.Exit(0); } func main() { var s string isdir:=false forcerename:=false argarray:=os.Args[1:]; r := regexp.MustCompile("[^a-zA-Z0-9\\.\\-/]+") if len(argarray) < 1 { help(); } if argarray[0] == "-h" { help(); } if argarray[0] == "-f" { forcerename=true argarray=argarray[1:] // strip "-f" } for i,f := range argarray { fileinfo, err := os.Lstat(f) if err != nil { fmt.Printf(" not found: %s\n",f); continue // nothing changed } isdir=false fbits:=fileinfo.Mode() //in new go version you can use: if filetypebits.IsRegular() { if fbits & os.ModeType !=0 { isdir=true } if ! forcerename { if isdir { fmt.Printf(" not a file: %s\n",f); continue // nothing changed } } if slashpos:=strings.Index(f,"/"); slashpos != -1 { if ! (isdir && slashpos == (len(f) - 1)){ // a directory name may have a slash at the end fmt.Printf(" %d: %s : can not rename files in other directories\n",i,f) continue } } s=r.ReplaceAllString(f,"_") if s == f { fmt.Printf(" %s\n",f); continue // nothing changed } fmt.Printf(" %d: %s -> %s :",i,f,s) if _, err := os.Lstat(s);err == nil { fmt.Println(" failed, file exists already"); continue } err_ren:=os.Rename(f,s) if err_ren!=nil { fmt.Print(" failed ") fmt.Println(err_ren); } else { fmt.Println(""); } } }