56438d61fd1c1b7d352a12c9b402f4a9

Basically, I have a large number of images to sort into folders that are to named after the file prefix (there are four files per prefix). For example, I need to move files named "0001A_hi_res.jpg", "0001A_lo_res.jpg", "0001A_prev.jpg" and "0001A_thumb.jpeg" into the folder named "0001A".

Here is what I have so far, but I think it could be better. I included a quick script to generate 130 fake test files.

#!/usr/bin/env ruby

#For each item in the input folder
Dir.foreach("input/") do |f|
  #Check if the item name ends in jpg
  if f.match(/jpg$/)
    #Split the filename into prefix and crap we don't care about
    prefix, crap = f.split("_")
    
    #Check if the destination folder exists
    if File.directory?("output/#{prefix}")
      #If it exists, just move the file to the folder
      FileUtils.mv("input/#{f}", "output/#{prefix}")
    else
      #Else, create the folder and move the file to it
      FileUtils.mkpath("output/#{prefix}")
      FileUtils.mv("input/#{f}", "output/#{prefix}")
    end
  end
end
#!/usr/bin/env bash

# Name of the folder to dump the fake files
mkdir -p input

# Create fake image files to process
for a in A B C D E F G; do
	for i in 1 2 3 4 5; do
		touch input/000"$i$a"_hi_res.jpg;
		touch input/000"$i$a"_lo_res.jpg;
		touch input/000"$i$a"_preview.jpg;
		touch input/000"$i$a"_thumbnail.jpg;
	done
done

COUNTED=`ls input/ | wc -w`;

echo "Created $COUNTED fake image files."

Refactorings

No refactoring yet !

A74c34f1043b833b1fcc86ce9f3521ee

Pavel Gorbokon

March 16, 2010, March 16, 2010 01:10, permalink

2 ratings. Login to rate!
#!/usr/bin/env ruby
require 'fileutils'

input  = File.expand_path(ARGV[0] || "input")
output = File.expand_path(ARGV[1] || "output")

Dir["#{input}/*.jpg"].each do |source|
  destination = File.join(output, File.basename(source).split('_').first)
  FileUtils.mkpath(destination) unless File.exists?(destination)
  FileUtils.mv(source, destination)
end

Your refactoring





Format Copy from initial code

or Cancel