I am trying to tie in a few different scripts I have noticed here and here link text Trying to get a basic script that will allow me to strip characters or rename files given a directory characters and file extension by user.
I am struggling to tie it all together. This is where I am so far.
require 'fileutils'
define renamer(strip, stripdetails)
# So this is a strip function.
def strip(str,char)
new_str = ""
str.each_byte do |byte|
new_str << byte.chr unless byte.chr == char
end
new_str
end
# and then retrieve details from user.
#Get directory of files to be changed.
def stripdetails(strip myname)
puts "Enter Directory containing files"
STDOUT.flush
oldname = gets.chomp
puts "what characters do you want to remove"
str = gets.chomp
puts "what file extension do files end in?"
fileXt = gets.chomp
end
#And I found this from stackoverflow(I don't have enuff credits to post another hyperlink)
old_file = "oldname"
new_file = strip(oldname,str)
FileUtils.mv(old_file, new_file)
Here's a refactoring of your code. It's not entirely clear from your question or your code, but I'm assuming you want to remove given characters from each filename in a directory.
Note that strip() method you copied from a blog post is entirely unnecessary, as it is a poor reimplementation of the built-in tr()
method.
#Given a directory, renames each file by removing
#specified characters from each filename
require 'fileutils'
puts "Enter Directory containing files"
STDOUT.flush
dir = gets.chomp
puts "what characters do you want to remove from each filename?"
remove = gets.chomp
puts "what file extension do the files end in?"
fileXt = gets.chomp
files = File.join(dir, "*.#{fileXt}")
Dir[files].each do |file|
new_file = file.tr(remove,"")
FileUtils.mv(file, new_file)
end