Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding files older than X hours using Ruby

Tags:

shell

ruby

I am in the middle of migrating all my bash scripts to Ruby. I am finding Ruby to be awesome however am stuck with a small problem. I am trying to move this script (basically find all logs older than x hours and process them). The Bash script looks something like this

find /var/log/myservice.log.* -mmin -120  -exec cp {} /home/myhomedir/mylogs/ \;

Of course I can loop through all the files, manually apply File.mtime on them and then identify the ones. However I want to understand if there is a much cleaner, one-liner to do this efficiently.

like image 272
Nitin Avatar asked Dec 06 '25 17:12

Nitin


1 Answers

One liner:

require 'fileutils'; Dir.glob("/var/log/myservice.log.*").each{|f| FileUtils.cp(f, '/home/myhomedir/mylogs/') if File.mtime(f) < (Time.now - (60*120)) }

Though I would prefer it spelled out a bit more:

require 'fileutils'
Dir.glob("/var/log/myservice.log.*").
  select{|f| File.mtime(f) < (Time.now - (60*120)) }.
  each{|f| FileUtils.cp(f, '/home/myhomedir/mylogs/') }
like image 184
Unixmonkey Avatar answered Dec 08 '25 08:12

Unixmonkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!