rubydir

Copying a file from one directory to another with Ruby


Hey I'm trying to move multiple files from one folder to another. In the FileUtils line I am trying to search through all of the 4 character folders in the destination folder and then paste the file in the folder with the same base name as the file.

#!/usr/bin/env ruby

require 'fileutils'

my_dir = Dir["C:/Documents and Settings/user/Desktop/originalfiles/*.doc"]
my_dir.each do |filename| 
  FileUtils.cp(filename, "C:/Documents and Settings/user/Desktop/destinationfolder/****/" + File.basename(filename, ".doc"))
end

Solution

  • Something like this should work.

    my_dir = Dir["C:/Documents and Settings/user/Desktop/originalfiles/*.doc"]
    my_dir.each do |filename|
      name = File.basename('filename', '.doc')[0,4]
      dest_folder = "C:/Documents and Settings/user/Desktop/destinationfolder/#{name}/"
      FileUtils.cp(filename, dest_folder)
    end
    

    You have to actually specify the destination folder, I don't think you can use wildcards.