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