Skip to content

Instantly share code, notes, and snippets.

@derekkraan
Created November 26, 2012 21:07
Show Gist options
  • Save derekkraan/4150607 to your computer and use it in GitHub Desktop.
Save derekkraan/4150607 to your computer and use it in GitHub Desktop.
Move all files with number greater than argument
def new_filename(num, filename)
if num.to_i < 9
"_0#{num.to_i+1}#{filename}"
elsif num.to_i < 99
"_#{num.to_i+1}#{filename}"
else
"#{num.to_i+1}#{filename}"
end
end
files = Dir['*']
shift = false
dry_run = false
ARGV.each do |arg|
dry_run = true if arg == '-n'
shift = $& if arg.to_s =~ /^[0-9]{1,4}$/
end
unless shift
puts 'invalid parameter; exiting'
exit 1
end
puts 'DRY RUN' if dry_run
LESS_HUNDRED = /^_([0-9]{2})(.*)/
HUNDRED_PLUS = /^([1-9][0-9]{2})(.*)/
queued_moves = []
temp_counter = 1
[LESS_HUNDRED, HUNDRED_PLUS].each do |regex|
files.select { |file| regex =~ file }.each do |file|
regex =~ file
if $1.to_i > shift.to_i
puts "renaming `#{file}` to `#{new_filename($1, $2)}`"
File.rename file, "__temp_#{temp_counter}" unless dry_run
queued_moves << ["__temp_#{temp_counter}", new_filename($1, $2)]
temp_counter += 1
end
end
end
unless dry_run
queued_moves.each do |move|
File.rename move[0], move[1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment