Created
June 22, 2020 02:52
-
-
Save kaczmarj/874c7ad2012ed5ba40639719a0703da4 to your computer and use it in GitHub Desktop.
Prepend filenames in a directory with an integer in ascending order of modified time. Integer prefixes are zero-padded based on the number of files in the directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"math" | |
"os" | |
"path" | |
"sort" | |
"strings" | |
) | |
func main() { | |
if len(os.Args) != 2 { | |
log.Fatalf("usage: %s path", os.Args[0]) | |
} | |
dirname := os.Args[1] | |
files, err := ioutil.ReadDir(dirname) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
// Sort in ascending order of modified time. | |
sort.Slice(files, func(i, j int) bool { | |
return files[i].ModTime().Unix() < files[j].ModTime().Unix() | |
}) | |
// Figure out how much padding is necessary (based on number of files). | |
padding := int(math.Ceil(math.Log10(float64(len(files))))) | |
formatter := fmt.Sprintf("%%0%dd", padding) | |
for j, file := range files { | |
newName := fmt.Sprintf(formatter, j) + fmt.Sprintf("_%s", file.Name()) | |
newName = strings.ReplaceAll(newName, " ", "_") | |
newName = path.Join(dirname, newName) | |
fmt.Printf("%s --> %s\n", file.Name(), path.Base(newName)) | |
err := os.Rename(path.Join(dirname, file.Name()), newName) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment