Skip to content

Instantly share code, notes, and snippets.

@Coro365
Last active August 24, 2016 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Coro365/19047d4a9fbaedb81949a862b3ec7fc1 to your computer and use it in GitHub Desktop.
Save Coro365/19047d4a9fbaedb81949a862b3ec7fc1 to your computer and use it in GitHub Desktop.
file name edit in regular expression
require "find"
Dir[File.dirname(__FILE__) + "/com_lib/*.rb"].each {|file| require file}
def yesno?(ms = "")
blue "#{ms}\nPlease press y/n\n> "
i = STDIN.gets
if /^y$|^Y$|^yes$|^Yes$|^YES$/ =~ i
return true
elsif /^n$|^N$|^no$|^No$|^NO$/ =~ i
return false
else
yesno?()
end
end
def blue ms
print "\e[35m" + ms + "\e[0m"
end
def user_ask
print "Regexp\n> "
patt = Regexp.new(STDIN.gets.chomp)
print "Replace str or Empty str or \"extract\"\n> "
repl = STDIN.gets.chomp
return patt, repl
end
def replace file_path
file_name = File.basename(file_path)
if file_name.match(PATT)
puts file_name
new_file_path = WD + "/" + file_name.gsub(PATT,REPL).to_s
puts File.basename(new_file_path)
$paths.push([file_path, new_file_path])
puts ""
end
end
def extract file_path
file_name = File.basename(file_path)
extension = File.extname(file_path)
extension = "" if extension.size > 4
if new_file_name = file_name.match(PATT)
puts file_name
new_file_path = WD + "/" + new_file_name[1].to_s + extension
puts File.basename(new_file_path)
$paths.push([file_path, new_file_path])
puts ""
end
end
def execute
$paths.each do |path|
crnt_path, new_path = path
File.rename(crnt_path, new_path)
end
end
PATT, REPL = user_ask
$paths = Array.new
ARGV[0].nil? ? WD=Dir.pwd : WD=ARGV[0]
print("Regexp: ")
p PATT
print("Replac: #{REPL}\n")
print("Dircty: #{WD}\n\n")
Find.find(WD) do |file_path|
next if File.basename(file_path) == ".DS_Store"
next if File.basename(file_path) == File.basename(WD)
if REPL == "extract"
unless $displayed
puts "! EXTRACT !"
$displayed = true
end
extract file_path
else
replace file_path
end
end
if yesno?("Execute?")
execute
puts "Done"
else
puts "Canceled"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment