Avdept
Avdept

Reputation: 2289

Making subdirectories while copying files

I have simple script that goes through txt file and copies files according to line in txt file

Here is it

require 'fileutils'


File.open("files.txt", "r") do |f|
  f.each_line do |line|
    line = line.chop  #need to remove \n symbol from like
    system("cp #{line} new/#{line}")
  end
end

In my txt files - there are file path in each like like:

app/helpers/api/v1/application_helper.rb

However when i run script it fails if there is no such directory inside my new folder. So either i have to create them manually to reflect folder structure as in my txt file, or create with script.

Is there any way how can i do this in my script?

Upvotes: 0

Views: 19

Answers (2)

Ahmad Sherif
Ahmad Sherif

Reputation: 6223

I see you're requiring fileutils but not using any of its methods. You can use it like this

require 'fileutils'

File.open("files.txt", "r") do |f|
  f.each_line do |line|
    line = line.chop  #need to remove \n symbol from like

    FileUtils.mkdir_p(File.dirname(line))
    FileUtils.cp(line, "new/#{line}")
  end
end

Upvotes: 1

Roland Mai
Roland Mai

Reputation: 31077

There are many ways to solve this. Here's one method:

require 'fileutils'

File.open("files.txt", "r") do |f|
  f.each_line do |line|
    line = line.chop
    system("mkdir -p new/#{File.dirname(line)}")
    system("cp #{line} new/#{line}")
  end
end

Upvotes: 2

Related Questions