Friday, May 25, 2012

Ruby one-liner: rename files

I wanted to strip a 20-character prefix, starting with the characters "IP_", from from a dozen XML files in a directory. Each file has a value of a different length following the prefix, e.g. "IP_stuff_foo.xml", "IP_stuff_bargain.xml", etc. I could probably do this by hand, or with a Windows batch file, but seeing as I'm learning Ruby (again), I thought I'd try to get it down as a Ruby one-liner, and here it is:

ruby -e 'Dir.glob("IP*.xml").each { |f| File.rename(f,f[24..-1]) }'
  • ruby -e calls Ruby to -"e"xecute the code in single quotes
  • Dir.glob("IP*").each finds all files in the current working directory that start with the string "IP". The glob() method returns an Array object, e.g. ["IP_foo.xml", "IP_bargain.xml", etc.], so the Array each() method returns "each" element in turn.
  • Each file name is passed in turn into the variable f in the block { ... }, where the File.rename() method does its magic.
  • File.rename takes two parameters, the name of the file to be renamed, and the new name for the file.
  • The new file name is a substring of the characters following the 20 character prefix. The substring is created by returning the remainder of the string after counting backwards, "-1", for "20" characters, f[20..-1].
  • Once File.rename() gets the substringed value, it renames the file.

1 comment:

  1. Perfect! Was looking for a solution like this for days now! Thank you very much for posting. Best regards Michel


Note: Only a member of this blog may post a comment.