Nitin
Nitin

Reputation: 53

Finding files older than X hours using 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.

Upvotes: 3

Views: 3609

Answers (1)

Unixmonkey
Unixmonkey

Reputation: 18784

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/') }

Upvotes: 11

Related Questions