Another reason I love Ruby

I was recently sent a set of photos and had literally hundreds to go through and didn’t have time to go through them all by hand. Plus, several of them were all minor variations on a theme. So I got the idea to just pick 24 random images, and discard the rest. I was working in Ruby at the time, so here’s what I did:

#!/usr/bin/env ruby

require 'fileutils'
include FileUtils

mark_for_removal = Dir.glob("*.jpg").shuffle[24..-1]

mark_for_removal.each {|f| rm f}

Here it is as a one-liner:

ruby -e 'require "fileutils" ; Dir.glob("*.jpg").shuffle[24..-1].each {|f| FileUtils.rm(f)}'

To be fair, this should also work on systems that have the GNU utils:

ls *.jpg | shuf | tail -n +25 | xargs rm

The beauty of the Ruby version is that it should work even if you don’t have the GNU utils.

Shane Simmons

Some guy from Southern Illinois