Since yesterday I was trying to write a script/program that would change filenames. Alongside learning golang I also started to make animations and for some reason Illustrator names every .png file I make like this - "name_working space 1 copy.png" and "* copy (number).png". I was tired of renaming those files manually and today I found this code and modified 1 line of it to get rid of "_working space 1 copy" but only from those files that have numbers. That leaves me with 2 files that are first frames of my animations and those are - "name_working space 1.png"; "name_working space 1 copy.png". I could totaly live with it by leaving those 2 blank but since I try to learn golang I wanted to ask if I can improve it to replace every single filename. I started learning monday this week.
import (
    "fmt"
    "log"
    "os"
    "path/filepath"
    "regexp"
)
func currentDir() {
    dir := "D:\\GoLang\\src\\gocourse\\renamefile\\rename"
    file, err := os.Open(dir)
    if err != nil {
        log.Fatalf("failed using this directory %s", err)
    }
    defer file.Close()
    list, err := file.Readdirnames(0)
    if err != nil {
        log.Fatalf("failed reading directory: %s", err)
    }
    re := regexp.MustCompile("_working space 1 copy ")
    for _, name := range list {
        oldName := name
        fmt.Println("Old name - ", oldName)
        newName := re.ReplaceAllString(oldName, "$1")
        fmt.Println("New Name - ", newName)
        err := os.Rename(filepath.Join(dir, oldName), filepath.Join(dir, newName))
        if err != nil {
            log.Printf("error renaming file: %s", err)
            continue
        }
        fmt.Println("File names have been changed")
    }
}
func main() {
    currentDir()
}
Here is a reimplementation of your code. However it is not complete, as you need to better clarify what the names look like before, and what they should look like after.
package main
import (
   "os"
   "path/filepath"
   "strings"
)
func main() {
   dir := `D:\GoLang\src\gocourse\renamefile\rename`
   list, err := os.ReadDir(dir)
   if err != nil {
      panic(err)
   }
   for _, each := range list {
      name := each.Name()
      newName := strings.ReplaceAll(name, "_working space 1 copy", "")
      os.Rename(filepath.Join(dir, name), filepath.Join(dir, newName))
   }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With