Skip to content

Instantly share code, notes, and snippets.

@isaacabraham
Last active November 20, 2018 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaacabraham/c6b190398381035dcd42bd09088ff662 to your computer and use it in GitHub Desktop.
Save isaacabraham/c6b190398381035dcd42bd09088ff662 to your computer and use it in GitHub Desktop.
let root = @"C:\Photos"
for srcDir in System.IO.Directory.GetDirectories root do
try
let srcDirName = (System.IO.Path.GetFileName srcDir).Split '-'
let year, month = int srcDirName.[0], int srcDirName.[1]
let targetDir = System.IO.Path.Combine(root, sprintf "%d-%d" year month)
System.IO.Directory.CreateDirectory targetDir |> ignore
for srcFile in System.IO.Directory.GetFiles srcDir do
System.IO.File.Move(srcFile, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName srcFile))
with _ -> printfn "Whoops!"
open System
open System.IO
/// Safely parses a string into a number
let (|Number|_|) n =
match Int32.TryParse n with
| true, number -> Some number
| _ -> None
/// Tries to get the year / month components from a folder name
let tryGetYearMonth (folder:string) =
let folderName = folder |> Path.GetFileName
match folderName.Split '-' |> Seq.toList with
| Number year :: Number month :: _ -> Some (folder, year, month)
| _ -> None
/// Lists all files to move from a folder, returning the destination as well
let getFilesToMove root (folder, year, month) =
let targetDirectory = Path.Combine(root, sprintf "%d-%d" year month)
folder
|> Directory.GetFiles
|> Array.map(fun file -> file, Path.Combine(targetDirectory, Path.GetFileName file))
/// Moves a file from source to dest, ensuring that the folder exists.
let safelyMove (source, dest) =
Directory.CreateDirectory (Path.GetDirectoryName dest) |> ignore
File.Move(source, dest)
let root = @"C:\Photos"
Directory.GetDirectories root
|> Array.choose tryGetYearMonth
|> Array.collect (getFilesToMove root)
|> Array.iter safelyMove
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment