Rename golang files without removing . from the extension

Asked

Viewed 120 times

-2

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

Follow the code link: 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
    }
}

1 answer

0


Solved

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 left Gist’s too:

Rename.go

Browser other questions tagged

You are not signed in. Login or sign up in order to post.