Dir.glob('*.{mp3,MP3}') do |file| match = file.match(/^(.+\()(\d+)(\).+)/) if (match == nil) puts "skipping #{file}" next end front, num, back = match.captures num = num.rjust(2, '0') newfile = front + num + back puts "renaming #{file} to #{newfile}" File.rename(file, newfile) end