Posted by: sureshamrita | July 5, 2008

How to rename a set of files using ruby

While switching to Ubuntu from Debian, in order to use the same home directory partition, I had to rename old configurations files to a new one so that ubuntu can freely create its own new configurations. At the same I was not willing to delete the old configurations files.

This is how it was done using ruby

  1. #!/usr/bin/ruby
  2. dir = “/mnt/home/suresh”
  3. files = Dir.entries(dir)
  4. files.each do |f|
  5. next if f == “.” or f == “..”
  6. if File.fnmatch(‘.*’,f) then
  7. puts f
  8. newname = f + “.olddeb”
  9. File.rename(f,newname)
  10. end
  11. end

Comments:
Line 5: To ignore the current and parent directories
LIne 6. I wanted to rename only files/directories starting with . (hidden files in unix)
Line 7. prints the current files – just for information
Line 8. the new name is old one with a .olddeb extension
Line 9. Does actual renaming

Advertisements

Responses

  1. hello sir,,i dont know anything about ruby,this is how u can do this on python//code starts hereimport glob,shutil;dir=glob.glob(“/mnt/home/suresh/.*”);for content in dir: shutil.move(content,content+”.old”)//code ends here…thats all!!!!glob function uses “.” as a wild card and brings all names starting in it.It never brings “.” and “..”.The for loop goes through this list content and renames every file/directory starting with “.” by appending “.old” to its end.

  2. Hi Anonymous student,I am slowly getting interested in python..I have one colleague who is a strong advocate…may be I would study python later….thanks for your comments


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Categories

%d bloggers like this: