Skip to content

Instantly share code, notes, and snippets.

@michbarsinai
Created August 12, 2020 08:52
Show Gist options
  • Save michbarsinai/b0756822efda6fb5881b6418eba74174 to your computer and use it in GitHub Desktop.
Save michbarsinai/b0756822efda6fb5881b6418eba74174 to your computer and use it in GitHub Desktop.
A simple Scala script to group files by month.
import java.nio.file._
import java.nio.file.attribute._
import scala.collection.JavaConverters._
import java.time._
import java.time.format._
val fmt = DateTimeFormatter.ofPattern("yyyy-MM")
val src = Paths.get(args(0))
val dst = Paths.get(args(1))
println( s"reading from: ${src.toAbsolutePath}")
println( s"writing to: ${dst.toAbsolutePath}")
println("Creating destination")
Files.createDirectory(dst)
println("...done")
def creationMonthOf( p:Path ):String = {
val attr = Files.readAttributes(p, classOf[BasicFileAttributes])
val createdAt = Instant.ofEpochMilli(attr.creationTime.toMillis).atZone(ZoneId.of("UTC"))
fmt.format(createdAt);
}
def moveFiles( monthStr:String, paths:Seq[Path]):Unit = {
val monthDir = dst.resolve(monthStr)
Files.createDirectory(monthDir)
paths.foreach( p => Files.move(p, monthDir.resolve(p.getFileName)) )
}
val groups = Files.list(src).iterator.asScala.toSeq.groupBy( creationMonthOf );
groups.keys.toSeq.sorted.foreach( k=> {
print(s"$k ${groups(k).length}...")
moveFiles(k, groups(k))
println("✅")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment