1

For example, in folder A, I have foo.jpg and bar.jpg. In folder B, I have foo.png and foobar.png. I only need one version of the file regardless of the extension, so I only want move foobar.png to folder A. How can I do this? This is a simple example, there are almost 2,000 files in folder B, so comparing manually would be very tedious.

1 Answer 1

1

Save the following as a text file and make it executable. Invoke it from the command line, passing in the paths to folder A and folder B.

#!/usr/bin/ruby

if ARGV.size != 2
    STDERR.print "#Usage: #{$0} source/folder destination/folder\n"
    exit 1
end

a = ARGV[0].chomp("/")
b = ARGV[1].chomp("/")
old_bases = Hash.new
Dir.foreach(b) do |f| 
    next if f =~ /^\./
    old_bases[f.sub(/\.[^.]*$/, "").downcase] = true
end
Dir.foreach(a) do |f|
    next if f =~ /^\./
    fbase = f.sub(/.[^.]*$/, "").downcase
    unless old_bases[fbase]
        File.rename( "#{a}/#{f}", "#{b}/#{f}" )
        old_bases[fbase] = true
    end
end

Script edited to check number of arguments, and fix error in File.rename

Edited again to ignore case. That is, don't move Bar.png if bar.jpg already exists.

2
  • Thanks for the answer, except I'm getting an error: undefined method `chomp' for nil:NilClass (NoMethodError)
    – Sum Guy
    Dec 28, 2014 at 16:52
  • You need to invoke the script with two parameters, the paths to the two folders. With 0 or 1 parameter, ARGV[0] and/or ARGV[1] will be nil, and can't be chomped. I probably have checked and put out an error message if ARGV.size != 2. You can do that, and/or hardcode the paths to the two folders. Come to think of it, I'll do it, since you may not know ruby.
    – ganbustein
    Dec 28, 2014 at 18:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .