[Golang] Find Last Modified File With Specific Name Prefix


This post shows you how to find the last modified file, name of which starts with specific prefx in Go.

We use ioutil.ReadDir to read files in the directory, but not in sub-directories. If you need to read also sub-directories, Use filepath.Walk.

package main

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

func findLastFileStartsWith(dir, prefix string) (lastFile os.FileInfo, err error) {
      files, err := ioutil.ReadDir(dir)
      if err != nil {
              return
      }

      for _, file := range files {
              if !file.Mode().IsRegular() {
                      continue
              }
              if strings.HasPrefix(file.Name(), prefix) {
                      if lastFile == nil {
                              lastFile = file
                      } else {
                              if lastFile.ModTime().Before(file.ModTime()) {
                                      lastFile = file
                              }
                      }
              }
      }

      if lastFile == nil {
              err = os.ErrNotExist
              return
      }
      return
}

func main() {
      file, err := findLastFileStartsWith(".", "myprefix")
      if err != nil {
              panic(err)
      }
      println(file.Name())
}

Tested on: Ubuntu Linux 17.10, Go 1.10.1

References

[1][Golang] Find Last Modified File Before Specific Time
[2][Golang] Find Oldest Modified File in Directory