Amazon.com Widgets
...not so private reflections of greg.newman
Categories & Search

Renaming a Thumb

While working on migrating a shopping cart for a client to a newer cart I found that the product thumbnail naming conventions were different between carts. I also noticed they had just shy of 2500 images to be renamed, so within 5 minutes time they were all prefixed with thumb_. Here's how I did it and hope someone else finds it useful.

&#060;?php $the_array = Array();<br /> $handle = opendir('images/uploads/thumbs/');<br /> <br /> while (false !== ($file = readdir($handle))) {<br /> &#xA0;&#xA0;&#xA0;if ($file != "." && $file != "..") {<br />&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;&#xA0;$the_array[] = $file;<br /> &#xA0;&#xA0;&#xA0;}<br /> }<br /> closedir($handle);<br /> <br /> foreach ($the_array as $element) {<br /> &#xA0;&#xA0;&#xA0;rename("images/uploads/thumbs/$element", "images/uploads/thumbs/thumb_".$element);<br /> }<br /> ?><br />


3 Comments

And here is an (untested) Ruby example. I couldn't resist :)

require 'fileutils'
Dir['images/uploads/thumbs'].each do |old|
  FileUtils.mv old, "images/uploads/thumbs/thumb_#{File.basename old}"
end

Way to go Jeremy.
I'll load her up and see if it works.
In the true spirit of ROR - much less code. So what did that take? ... 1 Minute.

Small nitpick for the PHP code... instead of:

if ($file != "." && $file != "..") {

...it would be better to use the following, which handles both cases and has the additional benefit of also ignoring hidden files:

if ($file[0] != '.') {

Leave a comment