Writing

Ruby Batch Rename Script

So I’ve recently gotten into scripting in ruby and with a couple of scripts you really can save yourself a lot of tedious work in the future. Here’s one i wrote that does a batch rename of all files in a given folder and its subfolders. You can do either of the following:

Enter 3 parameters:

  1. input directory
  2. search string
  3. replacement string
Or just enter 2 parameters in which case the search string will be removed from all files:
  1. input directory
  2. search string
Remember, to enter the parameters in that order, <input dir> <search string> [<replacement string>].

#!/usr/bin/ruby
# Dmitry Nedospasov
# Batch Rename
# 2 parameters: batchrename.rb <input dir> <search string>
# <search string> will be completely removed from all occurances
# 3 parameters: batrename.rb <input dir> <search string> <replacement string>
# all occurances of <search string> will be replaced with <replacement string>

require 'ftools'
def parseargs(arguments, stdin)
# puts arguments
dir = arguments[0]
oldExt = arguments[1]
newExt = arguments[2]
puts dir
puts oldExt
puts newExt
if oldExt == nil or dir == nil
puts 'Please enter atleast the first 2 parameters: '
puts ' <input directory> <search string> [<replacement string>]'
else
convertFromTo(dir,oldExt,newExt)
end
end
def convertFromTo(dir, oldExt, newExt)
files = Dir.entries(dir)
files.each do |f|
next if f == '.' or f == '..'
fullPath = dir + '/' + f
# fullPath = fullPath.gsub(' ','\ ')
if File.directory?(fullPath)
puts 'Found directory: ' + fullPath
convertFromTo(fullPath, oldExt, newExt)
else
if newExt == nil
newName = fullPath.gsub(oldExt,'')
else
newName = fullPath.gsub(oldExt,newExt)
end
if fullPath != newName
puts fullPath + ' -> ' + newName
File.rename(fullPath,newName)
end
end
end
end

parseargs(ARGV, STDIN)

and what you should get is something like this

russo@guevara:~/Desktop$ ./batchrename.rb . stpuid stupid
.
stpuid
stupid
Found directory: ./stupidtypo
./stupidtypo/stpuidtypo1.txt -> ./stupidtypo/stupidtypo1.txt
./stupidtypo/stpuidtypo10.txt -> ./stupidtypo/stupidtypo10.txt
./stupidtypo/stpuidtypo2.txt -> ./stupidtypo/stupidtypo2.txt
./stupidtypo/stpuidtypo3.txt -> ./stupidtypo/stupidtypo3.txt
./stupidtypo/stpuidtypo4.txt -> ./stupidtypo/stupidtypo4.txt
./stupidtypo/stpuidtypo5.txt -> ./stupidtypo/stupidtypo5.txt
./stupidtypo/stpuidtypo6.txt -> ./stupidtypo/stupidtypo6.txt
./stupidtypo/stpuidtypo7.txt -> ./stupidtypo/stupidtypo7.txt
./stupidtypo/stpuidtypo8.txt -> ./stupidtypo/stupidtypo8.txt
./stupidtypo/stpuidtypo9.txt -> ./stupidtypo/stupidtypo9.txt
Enjoy!!! and here’s the file for download

Tags , , , ,