How to Move a File with Ruby

How do I move a file with Ruby?

You can use FileUtils to do this.

#!/usr/bin/env ruby

require 'fileutils'

FileUtils.mv('/tmp/your_file', '/opt/new/location/your_file')

Remember; if you are moving across partitions, "mv" will copy the file to new destination and unlink the source path.

Move files to a target directory using Ruby

I think every line has extra character "\n" at the end. You need to strip it before.

FileUtils.mv(line.strip, target)

Moving files to a directory created on the fly

You could save the directory name to a variable, then reuse it:

require 'fileutils'
version = '2.1.6.0'
time = Time.now.strftime("%Y%m%d%H%M%S")
dirname = "ruby/bar/#{version}/#{time}"
FileUtils.makedirs dirname

FileUtils.mv 'foo.txt', dirname

FileUtils.makedirs returns the array containing paths to the folder it created. It's an array because you can call it with multiple folders to create:

FileUtils.makedir ["foo", "bar"]

If you want to reuse the FileUtils.makedirs result, you'll have to do something like this:

require 'fileutils'
version = '2.1.6.0'
time = Time.now.strftime("%Y%m%d%H%M%S")
dir = FileUtils.makedirs "ruby/bar/#{version}/#{time}"

FileUtils.mv 'foo.txt', dir.first

Move all files with same extension at once in ruby

You can do:

FileUtils.mv Dir.glob('*.sql'), '/some/output/dir/'

Move and Rename file on ftp site with Ruby

Use rename:

sftp.rename("luigi/List.csv", "luigi/archive/List_#{Time.now}.csv")

assuming luigi/archive exists.

To just delete, there is the remove function. See the Net::SFTP FAQ.



Related Topics



Leave a reply



Submit