42

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
KL-7
  • 46,000
  • 9
  • 87
  • 74
1dolinski
  • 479
  • 3
  • 9
  • 29
  • 1
    @KL-7, it's considered bad form to modify people's source code. Please use a comment to identify problems, such as the `#!` line you changed. – the Tin Man Mar 01 '12 at 16:21
  • 7
    @theTinMan, I don't think it's a bad idea to help new user with proper code indention. Regarding shebang I thought it was just a typo. – KL-7 Mar 01 '12 at 16:26

3 Answers3

72

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.

David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • 1
    You shouldn't be using the variable name "dest_folder", I copied the script without looking at it and it didn't work because I thought it should be a folder.. Could be my fault though.. ;) – Tim Baas May 14 '14 at 15:32
4

I had to copy 1 in every 3 files from multiple directories to another. For those who wonder, this is how I did it:

require 'fileutils'

# Print origin folder question

puts 'Please select origin folder'

# Select origin folder

origin_folder = gets.chomp

# Select every file inside origin folder with .png extension

origin_folder = Dir["#{origin_folder}/*png"]

# Print destination folder question

puts 'Please select destination folder'

# Select destination folder

destination_folder = gets.chomp

# Select 1 in every 3 files in origin folder
(0..origin_folder.length).step(3).each do |index|
  # Copy files
  FileUtils.cp(origin_folder[index], destination_folder)
end
Gabriel Guérin
  • 430
  • 2
  • 13
3

* is a wildcard meaning "any number of characters", so "****" means "any number of any number of any number of any number of characters", which is probably not what you mean.

? is the proper symbol for "any character in this position", so "????" means "a string of four characters only".

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • 1
    In shell pattern matching, actually `****` means any number of any characters followed by any number of any characters, followed by any nymber of any characters, followed by any nymber of any characters – akostadinov Aug 16 '17 at 09:28