Skip to content

Instantly share code, notes, and snippets.

@iwan
Created August 3, 2017 09:15
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 iwan/4711973475d3e2b000dc35e4de44d75e to your computer and use it in GitHub Desktop.
Save iwan/4711973475d3e2b000dc35e4de44d75e to your computer and use it in GitHub Desktop.
Ruby script used to move and reorder pdf files with a date in name
require 'fileutils'
require 'byebug'
# What it do
# ============
# It parse the 'dir' directory searching for
# pdf files with name matching the "xxx yyy - 2017-04-16"
# pattern and move them into a date named folder
# (like '2017-04-16')
# before: -------
# dir/
# Pinocchio.pdf
# Cenerentola - 2017-01-31.pdf
# Gatto con gli stivali - 2017-01-31.zip
# Biancaneve - 2017-01-31.pdf
# Cappuccetto rosso - 2017-02-16.pdf
# after: --------
# dir/
# Pinocchio.pdf
# Gatto con gli stivali - 2017-01-31.zip
# 2017-01-31/
# Cenerentola - 2017-01-31.pdf
# Biancaneve - 2017-01-31.pdf
# 2017-02-16/
# Cappuccetto rosso - 2017-02-16.pdf
dir = File.expand_path(File.dirname(__FILE__))
dir = "/Volumes/Discolo 1/Stampa"
def get_date(filename)
m = /.+ \- (\d{4}\-\d{2}\-\d{2})$/.match File.basename(filename, ".pdf")
if m && m[1]
m[1]
else
nil
end
end
Dir.chdir dir
pdfs = Dir.glob("*.pdf")
puts "Found #{pdfs.size} .pdf files in directory."
pdfs.each do |file|
if date = get_date(file)
Dir.mkdir(date) if !Dir.exists?(date)
dest = "#{date}/#{file}"
FileUtils.mv(file, dest) if !File.exists?(dest)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment