Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move all files with same extension at once in ruby

In terminal i could have used something like:

mv *.ext /some/output/dir/

I want to so the same in ruby. I can use system command for that under backticks (`) or using the system(), but how to achieve the same in ruby way?

I tried:

FileUtils.mv '*.sql', '/some/output/dir/'

This is not working as it looks specifically for a file name '*.sql'

like image 982
shivam Avatar asked Dec 20 '22 14:12

shivam


2 Answers

You can do:

FileUtils.mv Dir.glob('*.sql'), '/some/output/dir/'
like image 157
BroiSatse Avatar answered Dec 31 '22 20:12

BroiSatse


You need to use a Glob, as in:

Dir.glob('*.sql').each do|f|
  # ... your logic here
end

or more succinct:

Dir.glob('*.sql').each {|f| FileUtils.mv(f, 'your/path/here')}

Check the official documentation on FileUtils#mv which has even an example with Glob.

Update: If you want to be sure you don't iterate (although I wouldn't worry about it that much) you can always execute what you consider to be optimized in shell, directly from ruby, e.g.:

`mv *.ext /some/output/dir/`
like image 39
Kostas Rousis Avatar answered Dec 31 '22 20:12

Kostas Rousis