User7777
User7777

Reputation: 299

Multiple file basename in rake task

I have a folder with multiple pdf files and the file name are like this as below

1_abc.pdf
2_xyz.pdf
3_qwe.pdf

What is want to do is just get the first part of the file name that is

1
2
3

So I am trying to generate a rake task to get that working but I am not about to figure-out how to implement it on a multiple files.

namespace :request_document do
  desc "Expects to get a file or folder ..."
  task(:import_attachment, [:filename]) do |t, args|
    files = Dir.foreach("/Users/admin/Documents/Data/Attachments")
     puts files
      *This gives the list of all the files under the attachment folder*
  end
end

So I was thinking of using something like this

File.basename"1_abc.pdf".sub(/\_..*/, '')
=>  1

and this give the out as 1 which is what I need but I am not able to figure that out how to implement it on multiple files. Like it loops over all the files in the attachments folder and get me the first part of the filename. Please help me figure-out.

Upvotes: 0

Views: 261

Answers (1)

kriskova
kriskova

Reputation: 578

You can simply iterate over the filenames like:

Dir["/Users/admin/Documents/Data/Attachments/*"].each do |filename|
  puts File.basename(filename).sub(/\_.*/, '')
end

So with that the rake task would look something like this:

namespace :request_document do
  desc "Expects to get a file or folder ..."
  task(:import_attachment, [:path]) do |t, args|
    if File.directory?(args[:path])
      Dir["#{path}/*"].each do |file_path|
        puts File.basename(file_path).sub(/\_.*/, '')
      end
    else
      puts File.basename(args[:path]).sub(/\_.*/, '')
    end
  end
end

Upvotes: 1

Related Questions