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
}
}