Find from array and move

HI,

I’m needing to cull 900 files from about 3500 files in 100 different
directories.

I have an array with the 900 files ie. [“2100_01”, “2102_05”, “2105_04”,
“etc…”]

The files in question are named like so…“2100_01.aif”

Based on the array, I need to match/find these files from within the
100 directories and copy/move each one into a new single directory.

Can you help point me to the correct structure to accomplish this task.

Many Thanks

Chas

Hi,

You could use a glob (file pattern) to do this:

For example, if you are looking for every file with the name “x.txt” in
the directories “C:/a/” and “C:/b/”, you can write

Dir[‘C:/{a,b}/x.txt’]

This returns an array of the files found.

If you also want to include subdirectories, write

Dir[‘C:/{a,b}/**/x.txt’]

You can then move the file with FileUtils.move (you’ll have to include
the fileutils library first).

As an example code:

require ‘fileutils’

search_dirs = [‘C:/a/’, ‘C:/b/’]
search_files = [‘x’, ‘y’, ‘z’]
target_dir = ‘C:/z/’

todo: escape special characters like “{” and “}”

search_pattern = “{#{search_dirs.join ‘,’}}/**/”
search_files.each do |filename|
found = Dir[“#{search_pattern}/#{filename}.txt”]
case found.length
when 1
FileUtils.move found.first, target_dir
when 0
puts “File #{filename}.txt not found”
else
puts “File #{filename}.txt found more than once, didn’t move”
end
end

Chas C. wrote in post #1051998:

I’m needing to cull 900 files from about 3500 files in 100 different
directories.

I have an array with the 900 files ie. [“2100_01”, “2102_05”, “2105_04”,
“etc…”]

That would be an array of fileNAMES.

The files in question are named like so…“2100_01.aif”

Based on the array, I need to match/find these files from within the
100 directories and copy/move each one into a new single directory.

Pathname has quite a few nice tools for this. Something along these
lines should work:

require ‘set’
require ‘pathname’

array = … # as described
source = … # source directory path
target = … # target directory path

index = array.to_set # more efficient lookup
tgt = Pathname(target)

abort “Not a directory: #{tgt}” unless tgt.directory?

Pathname(source).find do |f|
f.file? and index.include? f.basename(’.aif’) and
f.rename(tgt + f.basename)
end

Kind regards

robert

Perfect! Thanks you guys!