Rename files in golang without removing. of extension

-2

I need to rename files from a directory by removing spaces and accents I solved both but had a side effect because I lost it. of the extension.

Follow the link from the code: Golang Playground

Code:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "strings"
    "unicode"

    "golang.org/x/text/transform"
    "golang.org/x/text/unicode/norm"
)

func main() {
    files, err := ioutil.ReadDir("./imgs_textos")
    if err != nil {
        log.Fatal(err)
    }

    for _, f := range files {
        normalize(f.Name())
    }
}

func normalize(nomeArquivo string) string {
    t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
    nomeNovo, _, _ := transform.String(t, nomeArquivo)
    s := strings.Join(strings.Fields(nomeNovo), "")
    fmt.Println(s)
    return s
}

func isMn(r rune) bool {
    return unicode.Is(unicode.Po, r) || unicode.Is(unicode.Mn, r)
}

func rename(nomeVelho, nomeNovo string) {
    err := os.Rename(nomeVelho, nomeNovo)
    if err != nil {
        fmt.Println(err)
        return
    }
}
    
asked by anonymous 27.03.2018 / 21:07

1 answer

0

Resolved

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "unicode"

    "golang.org/x/text/transform"
    "golang.org/x/text/unicode/norm"
)

func main() {
    dir := "./imgs_textos/"
    files, err := ioutil.ReadDir(dir)
    if err != nil {
        log.Fatal(err)
    }

    for _, f := range files {
        rename(dir+f.Name(), dir+normalize(f.Name()))
    }
}

func normalize(nomeArquivo string) string {
    t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
    nomeNovo, _, err := transform.String(t, nomeArquivo)
    if err != nil {
        log.Println(err)
    }
    fmt.Println(string(nomeNovo))
    return string(nomeNovo)
}

func isMn(r rune) bool {
    return unicode.Is(unicode.Mn, r) || unicode.IsSpace(r)
}

func rename(nomeVelho string, nomeNovo string) {
    err := os.Rename(nomeVelho, nomeNovo)
    if err != nil {
        fmt.Println(err)
        return
    }
}

I also left Gist where I need it:

Rename.go

    
28.03.2018 / 13:54