Skip to content

Instantly share code, notes, and snippets.

@ghthor
Created May 7, 2014 17:27
Show Gist options
  • Select an option

  • Save ghthor/594b3e02773ef27225d4 to your computer and use it in GitHub Desktop.

Select an option

Save ghthor/594b3e02773ef27225d4 to your computer and use it in GitHub Desktop.
Script To reformat all directories in a directory tree from $PWD/01-02-2006* -> $PWD/2006-01-02
package main
import (
"bufio"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
)
const dateFormatOld = "01-02-2006"
const dateFormatFix = "2006-01-02"
func main() {
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
directories := make([]string, 0, 20)
err = filepath.Walk(wd, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
if path == wd {
return err
}
scanner := bufio.NewScanner(strings.NewReader(info.Name()))
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
token := scanner.Text()
if strings.Count(token, "-") != 2 {
log.Fatal("unexpected Directory Format: ", info.Name())
}
directories = append(directories, info.Name())
break
}
}
return err
})
if err != nil {
log.Fatal(err)
}
directoriesFixed := make([]string, 0, len(directories))
for _, d := range directories {
scanner := bufio.NewScanner(strings.NewReader(d))
scanner.Split(bufio.ScanWords)
var nameFixed string
if !scanner.Scan() {
log.Fatal("unexpected scan of empty string")
} else {
dateToken := scanner.Text()
dateOld, err := time.Parse(dateFormatOld, dateToken)
if err != nil {
log.Fatal(err)
}
nameFixed = dateOld.Format(dateFormatFix)
}
for scanner.Scan() {
nameFixed += " " + scanner.Text()
}
directoriesFixed = append(directoriesFixed, nameFixed)
}
if len(directories) != len(directoriesFixed) {
log.Fatal("invalid fixed directory names array")
}
for i, _ := range directoriesFixed {
fmt.Printf("Renaming:\n%s ->\n%s\n", directories[i], directoriesFixed[i])
err := os.Rename(directories[i], directoriesFixed[i])
if err != nil {
log.Fatal(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment