123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- package file
- import (
- "os"
- "path/filepath"
- "sort"
- )
- // 搜索匹配文件,删除字典顺序排名靠前的文件
- // fmt.Sprintf("dumpTo%s.*.txt", name)
- func RemoveMatchedFiles(pattern string) error {
- // 使用filepath.Glob匹配文件
- matches, err := filepath.Glob(pattern)
- if err != nil {
- return err
- }
- // 遍历匹配到的文件路径
- var toUnlink []string
- var zeroFiles []string
- for _, path := range matches {
- // fi, err := os.Stat(path)
- // if err != nil {
- // continue
- // }
- fl, err := os.Lstat(path)
- if err != nil {
- continue
- }
- if fl.Mode()&os.ModeSymlink == os.ModeSymlink {
- continue
- }
- if fl.Size() == 0 {
- zeroFiles = append(zeroFiles, path)
- } else {
- toUnlink = append(toUnlink, path)
- }
- }
- sort.Strings(toUnlink)
- for _, path := range zeroFiles {
- os.Remove(path)
- }
- rotationCount := 7
- if rotationCount >= len(toUnlink) {
- return nil
- }
- toUnlink = toUnlink[:len(toUnlink)-int(rotationCount)]
- // 尝试删除文件
- for _, path := range toUnlink {
- os.Remove(path)
- }
- return nil
- }
|