Created
January 3, 2014 14:53
-
-
Save jsaak/8239152 to your computer and use it in GitHub Desktop.
recursive rename (convert) files in a directory
This file contains 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 | |
require 'optparse' | |
def parse_command_line | |
options = {} | |
optparse = OptionParser.new do |opts| | |
opts.banner = "Usage: #{__FILE__} [options] encoding path\n" + | |
"Encoding like UTF8-MAC or ISO-8859-2" | |
options[:inspect] = false | |
opts.on( '-i', '--inspecting', 'Do not convert, only show what will be done' ) do | |
options[:inspect] = true | |
end | |
opts.on( '-h', '--help', 'Display this screen' ) do | |
puts opts | |
exit | |
end | |
end | |
optparse.parse! | |
if ARGV[1].nil? | |
puts optparse.to_s | |
exit | |
end | |
unless Dir.exists?(ARGV[1]) | |
puts "Invalid path given: " + ARGV[0] | |
exit | |
end | |
options[:encoding]= ARGV[0] | |
options[:path]= ARGV[1].chomp('/')+'/' | |
return options | |
end | |
options = parse_command_line | |
Dir.glob(options[:path] + "**/*").sort{|x| x.size}.each do |name| | |
parts = name.split('/') | |
original = parts[-1] | |
modified = parts[-1].encode('UTF-8',options[:encoding]) | |
newname = (parts[0..-2] + [modified]).join('/') | |
if name != newname | |
if options[:inspect] | |
puts original + " -> " + modified | |
else | |
File.rename(name, newname) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment