1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package main
- import (
- "fmt"
- "os"
- "path"
- "regexp"
- "strconv"
- "strings"
- "time"
- )
- func main() {
- _, err := GetAllFile("/data/mongobackupdata/storage")
- if err != nil {
- fmt.Println(err)
- return
- }
- fmt.Println("备份文件命名成功")
- }
- func GetAllFile(pathname string) ([]string, error) {
- result := []string{}
- fis, err := os.ReadDir(pathname)
- if err != nil {
- fmt.Printf("读取文件目录失败,pathname=%v, err=%v \n", pathname, err)
- return result, err
- }
- // 所有文件/文件夹
- for _, fi := range fis {
- fullname := pathname + "/" + fi.Name()
- // 是文件夹则递归进入获取;是文件,则压入数组
- if fi.IsDir() {
- temp, err := GetAllFile(fullname)
- if err != nil {
- fmt.Printf("读取文件目录失败,fullname=%v, err=%v", fullname, err)
- return result, err
- }
- result = append(result, temp...)
- } else {
- // 匹配时间戳命名的文件
- re := regexp.MustCompile(`\d{10}`)
- strs := re.FindAllString(fullname, -1)
- if len(strs) > 0 {
- // 格式化匹配到的时间
- backupTime := strs[0]
- backup, _ := strconv.Atoi(backupTime)
- tm := time.Unix(int64(backup), 0)
- timestr := tm.Format("2006-01-02 15:04:05")
- // 拼接需要重命名的文件带路径字符串
- suffix := path.Ext(fullname)
- fileSlice := strings.Split(fullname, "-")
- filePrefix := fileSlice[:len(fileSlice)-1]
- renamefile := strings.Join(filePrefix, "-") + "-" + timestr + suffix
- // 重命名文件
- os.Rename(fullname, renamefile)
- }
- result = append(result, fullname)
- }
- }
- return result, nil
- }
|