Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Remove files older than N days from "/path/to/files" - Requires filename starting by YYYY-MM-DD
// MIT License <https://opensource.org/licenses/MIT> - Copyright (c) 2018 Miguel Dorta
package main
import (
"fmt"
"os"
"path/filepath"
"strconv"
"time"
)
func main() {
if len(os.Args) != 3 {
fmt.Println("Usage: rmOldFiles <path> <days>")
os.Exit(1)
}
days, err := strconv.Atoi(os.Args[2])
if err != nil {
panic(err)
}
now := time.Now().Unix()
list, err := readDir(os.Args[1])
if err != nil {
panic(err)
}
for _, f := range list {
if f.IsDir() {
continue
}
fTime, err := getFileDate(f.Name())
if err != nil {
fmt.Println(err.Error())
continue
}
if (now - fTime) < int64(days * 24 * 60 * 60) {
continue
}
os.Remove(filepath.Join(os.Args[1], f.Name()))
}
}
func getFileDate(fName string) (int64, error) {
y, err := strconv.Atoi(fName[:4])
if err != nil {
return 0, fmt.Errorf("error parsing year in file: %s", fName)
}
m, err := strconv.Atoi(fName[5:7])
if err != nil {
return 0, fmt.Errorf("error parsing month in file: %s", fName)
}
d, err := strconv.Atoi(fName[8:10])
if err != nil {
return 0, fmt.Errorf("error parsing day in file: %s", fName)
}
return time.Date(y, time.Month(m), d, 0, 0, 0, 0, time.UTC).Unix(), nil
}
func readDir(path string) ([]os.FileInfo, error) {
f, err := os.Open(os.Args[1])
if err != nil {
return nil, err
}
defer f.Close()
fList, err := f.Readdir(-1)
if err != nil {
return nil, err
}
return fList, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment