ruby renumber.rb ディレクトリのパス ファイルの接頭語 連番を0で埋めた後の桁数

スクリプトのソースコード:


path = ARGV[0]
pre  = ARGV[1]
num  = ARGV[2].to_i
Dir.foreach(path){|file|
  if file != ".." && file != "." then
    ext  = File.extname(file)
    body = file[pre.size..-1 * (ext.size + 1)]
    newbody = pre + body.rjust(num, "0")
    from = path + "/" + file
    to   = path + "/" + newbody + ext
    File.rename(from, to)
    puts "rename: " + from + "\t->\t" + to
  end
}

使用例:


C:\>ruby renumber.rb ./index_files index 4
rename: ./index_files/index0.png    ->      ./index_files/index0000.png
rename: ./index_files/index1.png    ->      ./index_files/index0001.png
rename: ./index_files/index10.png   ->      ./index_files/index0010.png
rename: ./index_files/index100.png  ->      ./index_files/index0100.png
rename: ./index_files/index1000.png ->      ./index_files/index1000.png
rename: ./index_files/index1001.png ->      ./index_files/index1001.png
rename: ./index_files/index1002.png ->      ./index_files/index1002.png
rename: ./index_files/index1003.png ->      ./index_files/index1003.png
rename: ./index_files/index1004.png ->      ./index_files/index1004.png
rename: ./index_files/index1005.png ->      ./index_files/index1005.png
rename: ./index_files/index1006.png ->      ./index_files/index1006.png
rename: ./index_files/index1007.png ->      ./index_files/index1007.png
rename: ./index_files/index1008.png ->      ./index_files/index1008.png
rename: ./index_files/index1009.png ->      ./index_files/index1009.png
rename: ./index_files/index101.png  ->      ./index_files/index0101.png
rename: ./index_files/index1010.png ->      ./index_files/index1010.png
rename: ./index_files/index1011.png ->      ./index_files/index1011.png
rename: ./index_files/index1012.png ->      ./index_files/index1012.png
rename: ./index_files/index1013.png ->      ./index_files/index1013.png

tags: Ruby zurazure

Posted by NI-Lab. (@nilab)