Saari Development

Ali Rizvi's Technical Blog as a Professional Software Development Engineer

Ruby: Add a prefix to all files in a directory

leave a comment »

I found myself looking for a way to rename all files in a directory by appending a prefix and couldn’t find a utility to do such a renaming after quick search so I wrote my own.

# Quick script to bulk prepend prefix to filenames to all files in a directory
# Also strips any spaces in the filename
# Example usage : ruby prepend_rename.rb Disc1_ C:\AudioBook\Disc1\

raise "Prefix and Directory are required" if ARGV.size < 2

prefix = ARGV[0]
dir = ARGV[1]

raise "Non-word character prefix #{prefix}" unless prefix =~ /^\w+$/
raise "No such directory: #{dir}" unless Dir.exists?(dir)

Dir.entries(dir).each do |file|
 next if
 new_name = prefix + file.gsub(/\s+/, '')
 File.rename(file, new_name)


Written by imsaar

February 7, 2010 at 6:11 pm

Posted in code, ruby, windows

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: