Search code examples
rubyfile-iofile-handlingfileutils

Moving files on external volume with Ruby fileutils?


I've run into what feels like a pretty basic error, but I can't find any documentation about what I'm struggling with. Here's the code:

require "fileutils"

def new_name(fn, dest = '/Volumes/External/Different\ Sublevel/Renamed', append = '_01')
    ext = File.extname(fn)
  File.join( dest, File.basename(fn, ext) + append + ext )
end

Dir[ '/Volumes/External/Example/Sublevels/**/*.xml' ].
select { |fn| File.file? fn }.
each   { |fn| FileUtils.cp fn, new_name(fn) }

All I'm trying to do is move some files (non-destructively) and append the filename. It works great on some local files, but I did multiple levels of ../../../ to get it to work. Is there something special about specifying external drives?


Solution

  • You are trying to pass string with escaped space character that is not interpreted inside apostrophes. You have to either omit the escape character

    '/Volumes/External/Different Sublevel/Renamed'

    or put it in double-quotes

    "/Volumes/External/Different\ Sublevel/Renamed".

    String created with apostrophes interprets only two escape sequences: backslash '\\' and apostrophe itself '\'' .

    Details about Ruby strings at wikibooks.org