Skip to content

Instantly share code, notes, and snippets.

@masciugo
Last active August 29, 2015 14:21
Show Gist options
  • Save masciugo/9319a809efb6fdff5307 to your computer and use it in GitHub Desktop.
Save masciugo/9319a809efb6fdff5307 to your computer and use it in GitHub Desktop.
Renaming file in directory
#!/usr/bin/env ruby
# vedi gist at https://gist.github.com/masciugo/9319a809efb6fdff5307
require 'rubygems'
require 'byebug'
require 'logger'
require 'fileutils'
target_dir = case ARGV.size
when 0
File.join(ENV['HOME'],'Downloads')
when 1
ARGV.first
else #usage
puts
puts
puts "usage: ./quotidie_rename.rb <target_dir_path>"
exit 0
end
raise "directory #{target_dir} not existing" unless File.exists? target_dir
TR = {
'cds' => 'Corriere della Sera',
'gds' => 'Gazzetta dello Sport',
'mf' => 'Milano Finanza',
's24h' => 'Sole 24 Ore',
'fatto' => 'Fatto Quotidiano',
'stampa' => 'Stampa',
'foglio' => 'Foglio',
'vdr' => 'Venerdi di repubblica',
'venerdi' => 'Venerdi di repubblica',
'internazionale' => 'Internazionale',
'ac_' => 'Altro Consumo',
'espresso' => 'Espresso',
'manifesto' => 'Manifesto',
'libero' => 'Libero',
'repubblica' => 'Repubblica'
}
REGEXP = /(#{TR.keys.join('|')})(.+)\.pdf\Z/i
REGEXP_DATE = /\A\d{8}\Z/
REGEXP_NUM = /n\.\d+/i
Dir.chdir(target_dir) do |variable|
puts "reading directory #{target_dir}"
Dir.glob('*.pdf') do |fn|
begin
if data = REGEXP.match(fn)
name = TR[data[1].downcase]
suffix = if REGEXP_DATE.match(data[2])
Date.parse(data[2]).to_s
elsif REGEXP_NUM.match(data[2])
REGEXP_NUM.match(data[2]).to_s
else
data[2]
end
new_fn = [name,suffix].join(' - ') + '.pdf'
if File.exists? new_fn
puts "skipping #{fn}. Already exists"
else
puts "RENAMING #{fn} to #{new_fn}"
FileUtils.copy(fn,new_fn)
end
else
puts "skipping #{fn}"
end
rescue SystemExit
exit 0
rescue Exception => e
puts "Problem with file #{fn}, skipped. Backtrace:"
puts e.backtrace
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment