6

[Golang] Find Files Older Than One Day

 2 years ago
source link: http://siongui.github.io/2018/03/25/go-find-files-modified-longer-than-one-day/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Find Files Older Than One Day

March 25, 2018

Find files of which modified time is older than one day in Go.

  1. Use ioutil.ReadDir or filepath.Walk to find files: if you want to find all files including sub-directories, use filepath.Walk. If you just want files in a directory but not in sub-directories, use ioutil.ReadDir. Here we use ioutil.ReadDir in our example.
  2. use time.Now() to get current time and use func (Time) Sub to perform subtraction of current time and modified time of file. If the duration is greater than 24 hours, than it's more than one day.

The following code is the implementation of above idea:

import (
      "io/ioutil"
      "os"
      "time"
)

func isOlderThanOneDay(t time.Time) bool {
      return time.Now().Sub(t) > 24*time.Hour
}

func findFilesOlderThanOneDay(dir string) (files []os.FileInfo, err error) {
      tmpfiles, err := ioutil.ReadDir(dir)
      if err != nil {
              return
      }

      for _, file := range tmpfiles {
              if file.Mode().IsRegular() {
                      if isOlderThanOneDay(file.ModTime()) {
                              files = append(files, file)
                      }
              }
      }
      return
}

Tested on: Ubuntu Linux 17.10, Go 1.10


References:

[2]How To Find And Delete Files Older Than X Days In Linux - OSTechNix

[3]10 Examples of find command in Unix and Linux | System Code Geeks - 2018

[4]Mocking system time in tests : golang


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK