Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Created June 26, 2011 21:40
Show Gist options
  • Save earlonrails/1047995 to your computer and use it in GitHub Desktop.
Save earlonrails/1047995 to your computer and use it in GitHub Desktop.
Ruby version of rename function in linux for use with mac osx. Rename files ex. rename .txt .bak *.txt
#!/usr/bin/ruby
opts = []
args = []
ARGV.each do |a|
if a =~ /^(-[a-zA-Z]+)/
opts << a
else
args << a
end
end
if args.empty? && opts.empty?
puts "ex. rename .bak .txt *.bak"
puts "or rename 'regex' *.mp3"
exit
end
arg_one = args[0]
arg_two = args[1]
files = nil
check_args = Proc.new {|opt|
ex_opts = {:r => "downcase", :n => ""}
if arg_one.nil? || arg_two.nil?
if opt
puts "option -#{opt} requires two arguments"
puts "ex. rename -#{opt} #{ex_opts[opt.to_sym]} *"
else
puts "rename requires two arguments"
end
exit
end
files = opt == "-r" || opt.nil? ? args.drop(1) : args
if files.size == 0
puts "no files matched: #{arg_two}"
exit
end
}
opts.each do |o|
# TODO add option support
# do something
# puts o
case o
# option -r for ruby means do a ruby function to the file name
# rename -r downcase *
when /-.*r.*/
check_args.call(o)
files.each do |f|
begin
was = f
f = eval("f.dup.#{arg_one}")
next if was == f
File.rename(was, f)
rescue
puts "option -r requires the second argument to be file names"
puts "ex. rename -r upcase fIleThatItHoUgHtExIst.txt"
end
end
exit
# option -n for numbers means add a number to file name
# rename -n *
when /-.*n.*/
check_args.call(o)
n = 1
files.each do |f|
begin
was = f
f = File.basename(f, File.extname(f)) + n.to_s + File.extname(f)
n += 1
next if was == f
File.rename(was, f)
rescue
puts "option -n requires the 1st argument be file names"
puts "ex. rename -n *.txt"
end
end
exit
when /-.*h.*/
puts "Usage: rename .bak .txt *.bak"
puts "or rename 'regex' *.mp3"
puts "or rename -r [ruby function] *.txt"
puts "or rename -n *.txt"
puts "or rename -h"
exit
else
# default option ?
end
end
# change extensions?
if arg_one =~ /\.\w{1,4}$/
files = args.drop(2) # `ls *#{arg_three}`
files.each do |f|
f = f.strip
f_name = File.basename(f, arg_one)
if f_name
File.rename(f, f_name + arg_two) # `mv #{i} #{f_name}#{arg_two}`
end
end
# change filenames
else
check_args.call(nil)
files.each do |f|
f = f.strip
f_name = File.basename(f)
nf_name = f_name.gsub(Regexp.new(arg_one), '')
if f_name
File.rename(f_name, nf_name) # `mv #{f_name} #{nf_name}`
end
end
end
rename(){
ruby ~/rename.rb $*
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment