Skip to content

Instantly share code, notes, and snippets.

@Yuiki Yuiki/rename.rb
Created Dec 23, 2016

Embed
What would you like to do?
一括リネーム
require 'fileutils'
require 'date'
if ARGV.size < 2
STDERR.print "Usage: ruby #{$0} <path> <name>\n"
exit(1)
end
PATH = ARGV[0].gsub(File::ALT_SEPARATOR) {File::SEPARATOR}
NAME = ARGV[1]
DATETIME = DateTime.now.strftime("%Y%m%d%H%M%S")
files = Dir.glob(PATH + "/*")
files.sort! do |a, b|
File.stat(a).ctime.strftime("%Y%m%d%H%M%S") <=> File.stat(b).ctime.strftime("%Y%m%d%H%M%S")
end
files.each.with_index(1) do |filename, index|
dirname = File.dirname(filename)
basename = File.basename(filename)
extname = File.extname(filename)
newfilename = dirname + '/' + NAME + '_' + format("%04d", index.to_s) + '_' + DATETIME + extname
if !File.exists?(newfilename)
File.rename(filename, newfilename)
print "[" + index.to_s + "]" + basename + "->" + NAME + '_' + format("%04d", index.to_s) + '_' + DATETIME + extname + "\n"
else
raise "Exist new file name.\n"
end
end
print "Finish!\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.