file.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package file
  2. import (
  3. "os"
  4. "path/filepath"
  5. "sort"
  6. )
  7. // 搜索匹配文件,删除字典顺序排名靠前的文件
  8. // fmt.Sprintf("dumpTo%s.*.txt", name)
  9. func RemoveMatchedFiles(pattern string) error {
  10. // 使用filepath.Glob匹配文件
  11. matches, err := filepath.Glob(pattern)
  12. if err != nil {
  13. return err
  14. }
  15. // 遍历匹配到的文件路径
  16. var toUnlink []string
  17. var zeroFiles []string
  18. for _, path := range matches {
  19. // fi, err := os.Stat(path)
  20. // if err != nil {
  21. // continue
  22. // }
  23. fl, err := os.Lstat(path)
  24. if err != nil {
  25. continue
  26. }
  27. if fl.Mode()&os.ModeSymlink == os.ModeSymlink {
  28. continue
  29. }
  30. if fl.Size() == 0 {
  31. zeroFiles = append(zeroFiles, path)
  32. } else {
  33. toUnlink = append(toUnlink, path)
  34. }
  35. }
  36. sort.Strings(toUnlink)
  37. for _, path := range zeroFiles {
  38. os.Remove(path)
  39. }
  40. rotationCount := 7
  41. if rotationCount >= len(toUnlink) {
  42. return nil
  43. }
  44. toUnlink = toUnlink[:len(toUnlink)-int(rotationCount)]
  45. // 尝试删除文件
  46. for _, path := range toUnlink {
  47. os.Remove(path)
  48. }
  49. return nil
  50. }