[golang]批量修改名称

package main

import (
	"fmt"
	"io/fs"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
)

func myWalkFunc(path string, info fs.FileInfo, err error) error {
	ext := ".rmvb"
	// log.Printf("--> path: %v, file: %v, ext: %v", path, info.Name(), filepath.Ext(path))

	if info.IsDir() {
		return nil
	}

	if filepath.Ext(path) != ext {
		return nil
	}

	// get file name without ext
	filename := info.Name()[:len(info.Name())-len(ext)]

	//[电影天堂www.dygod.cn][三国演义][第20集][DVD高清晰版]
	// [电影天堂www.dy2018.net]冰与火之歌:权力的游戏第一季01集中英双字[1024分辨率]
	re := regexp.MustCompile(`-?[0-9]\d*集`)
	strMatch := re.FindString(filename)
	if strMatch == "" {
		return fmt.Errorf("未找到关键字")
	}
	log.Printf("file: %v, match: %v, len=%v\n", filename, strMatch, len(strMatch))
	strMatch = strMatch[:len(strMatch)-len("集")]

	nMatch, err := strconv.Atoi(strMatch)
	if err != nil {
		return err
	}
	strNewFileName := fmt.Sprintf("权力的游戏S01EP%02d.%v", nMatch, ext)
	log.Printf("match: %v, [%v] => [%v]\n", strMatch, filename, strNewFileName)
	os.Rename(info.Name(), strNewFileName)

	return nil
}

func main() {
	fmt.Println("---------------- 批量修改名称 --------------------")
	fmt.Scan()

	curdir, err := os.Getwd()
	if err != nil {
		log.Fatalln(err)
	}
	//retiver dictery
	err = filepath.Walk(curdir, myWalkFunc)
	if err != nil {
		log.Fatalln(err)
	}

	i := 0
	fmt.Scan(&i)
}

posted @ 2022-04-10 14:15  jiftle  阅读(215)  评论(0编辑  收藏  举报