Webtm Webtm - 1 year ago 101
Ruby Question

Passing the contents of a file to FileUtils.cp

file = 'list.txt'
fileArray = []

list_open = File.open(file, "r")
list_open.each_line { |line|
fileArray.push line

fileArray.each { |x| puts x }
fileArray.each { |x| FileUtils.cp x, "/home/user/scripts/" }

The contents of
is just a path to a file. I want to read from the file and pass it to
here and copy it to

When I run this script, here is the error I receive:

/usr/local/lib/ruby/2.1/fileutils.rb:1401:in `initialize': No such file or directory @ rb_sysopen - /home/user/test.txt (Errno::ENOENT)
from /usr/local/lib/ruby/2.1/fileutils.rb:1401:in `open'
from /usr/local/lib/ruby/2.1/fileutils.rb:1401:in `copy_file'
from /usr/local/lib/ruby/2.1/fileutils.rb:483:in `copy_file'
from /usr/local/lib/ruby/2.1/fileutils.rb:400:in `block in cp'
from /usr/local/lib/ruby/2.1/fileutils.rb:1579:in `block in fu_each_src_dest'
from /usr/local/lib/ruby/2.1/fileutils.rb:1593:in `fu_each_src_dest0'
from /usr/local/lib/ruby/2.1/fileutils.rb:1577:in `fu_each_src_dest'
from /usr/local/lib/ruby/2.1/fileutils.rb:399:in `cp'
from ./for_Test.rb:12:in `block in <main>'
from ./for_Test.rb:12:in `each'
from ./for_Test.rb:12:in `<main>'

Answer Source

Recall that each line in a file necessarily ends with a newline ("\n"). You need to remove it, which is easy with String#chomp:

list_path = "list.txt"
filenames = []

File.open(list_path, "r") do |list|
  list.each_line do |line|

...or more succinctly:

filenames = File.open(list_path, "r") do |list|
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download