Created
August 10, 2012 15:31
-
-
Save o-eight/3315059 to your computer and use it in GitHub Desktop.
指定されたフォルダ内の指定された拡張子のファイルについて、更新日時順で連番をファイル名に付加するスクリプト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# coding: utf-8 | |
# | |
# 指定されたフォルダ内の指定された拡張子のファイルを更新日時順で連番を付ける | |
require 'rubygems' | |
require 'thor' | |
class App < Thor | |
#この辺の使い方のメッセージはいつかなんとかする。 | |
desc "rename PATH", "Add prefix serial number to target folder's files." | |
method_option :digit, :type => :numeric, :aliases => "-d", :default => 3, :desc => "number of digits" | |
method_option :reverse, :type => :boolean, :aliases => "-r", :default => false, :desc => "Earlist file will be youngest number." | |
method_option :extension, :type => :array, :aliases => "-e", :default => ["jpg", "png"], :desc => "Set space-separted target file extension" | |
def rename(path) | |
#指定パスがディレクトリじゃなかったら、メッセージを吐いて抜ける。うまく書けない。 | |
at_exit{puts "Abort: #{path} is not directory."} unless FileTest::directory?(path) | |
#カレントディレクトリの移動 | |
Dir.chdir(path) | |
extensions = Array.new | |
#拡張子とパスをくっつけて、glob用の文字列作成 | |
options[:extension].each do |ext| | |
extensions << "*." + ext | |
end | |
files = Dir.glob(extensions) | |
#ファイルリスト(ファイル名と更新日時のハッシュ)を作成 | |
filelist = Hash.new | |
files.each do |file| | |
stat = File.stat(file) | |
filelist.store(file, stat.mtime) | |
end | |
#ソートして指定桁数で頭に連番を追加 | |
unless options[:reverse] then | |
filelist.sort{|a, b| a[1] <=> b[1]}.each_with_index do |harr, idx| | |
File.rename(harr[0], sprintf("%#0#{options[:digit]}d",idx) + "_" + harr[0]) | |
end | |
else | |
filelist.sort{|a, b| b[1] <=> a[1]}.each_with_index do |harr, idx| | |
File.rename(harr[0], sprintf("%#0#{options[:digit]}d",idx) + "_" + harr[0]) | |
end | |
end | |
end | |
end | |
App.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment