Last active
October 5, 2018 14:34
-
-
Save PatrickWalker/1814906ebd12166d7dea6faad6b885ed to your computer and use it in GitHub Desktop.
Renaming Files in Go using a rename function
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" | |
"io/ioutil" | |
"log" | |
"os" | |
"strings" | |
) | |
func main() { | |
files, err := ioutil.ReadDir(".") | |
if err != nil { | |
log.Fatal(err) | |
} | |
for _, file := range files { | |
newName, ok := rename(file.Name()) | |
if ok { | |
err := os.Rename(file.Name(), newName) | |
if err != nil { | |
log.Println(err) | |
} else { | |
log.Printf("Renamed %s to %s \n", file.Name(), newName) | |
} | |
} else { | |
log.Printf("Skipping %s as no need to rename \n", file.Name()) | |
} | |
} | |
} | |
func rename(oldName string) (newName string, shouldRename bool) { | |
s := strings.Split(oldName, ".") | |
if len(s) != 3 { | |
//this is not named in our current way so we get out | |
return | |
} | |
//if file is named .down then add a U to start | |
switch s[1] { | |
case "up": | |
s[0] = fmt.Sprintf("V%s", s[0]) | |
case "down": | |
s[0] = fmt.Sprintf("U%s", s[0]) | |
default: | |
return | |
} | |
//replace all instance of _ with - | |
s[0] = strings.Replace(s[0], "_", "-", -1) | |
//replace first _ with __ | |
s[0] = strings.Replace(s[0], "-", "__", 1) | |
//join the bits removing the up/down | |
newName = fmt.Sprintf("%s.%s", s[0], s[2]) | |
shouldRename = true | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment