Jack Eccleshall
Jack Eccleshall

Reputation: 625

Search a file directory for a file or multiple files with the same starting characters

I am trying to create a ruby script that will open a csv file and search a directory for files depending on the contents of each line in the csv file

e.g

**.csv file**    **directory**
13456            13456.jpg
13567            13456a.jpg
13687            13456b.jpg
                 13567.jpg
                 13687.jpg
                 13687a.jpg

Once i have found that i would then like to copy the files found into a folder called Keep

Im getting stuck figuring out how to search a directory

so ive done a bit of coding but im still stuck

 #require 'fileutils'
require 'spreadsheet'

input = "/Users/eccleshall/ImageCleanUp/" #where images are stored
output = "/Users/eccleshall/ImageCleanUp/Keep" #where images will be copied to

book = Spreadsheet.open '/Users/eccleshall/Desktop/ImageCleanUpScript/B002.xls' #opens workbook

sheet1 = book.worksheet 0 # sets worksheet

sheet1.each do |row| #for each row output
    puts row

    Dir.glob("/Users/eccleshall/ImageCleanUp/" row).each do|f| #search /Users/eccleshall/ImageCleanUp/ for files startig with row
        puts f
    end
end

i keep getting a error when run though

ImageCleanUp.rb:14: syntax error, unexpected tIDENTIFIER, expecting ')' ...s/eccleshall/ImageCleanUp/" row).each do|f| #search /Users/e...

any ideas anyone?

Upvotes: 0

Views: 317

Answers (1)

fmendez
fmendez

Reputation: 7338

You can search it the following way:

require 'fileutils'
Dir.glob('/path_to_file_directory/*.csv').each do |f|  # you can replace the extension you're looking for.
     # the 'f' will give a string representing the path of each file
end

Alternatively:

Dir.foreach('/path_to_file_directory/') do |i|
  next if i == '.' or i == '..'
  # do something with each file
end 

Upvotes: 1

Related Questions