Thursday, April 12, 2012

Command one liners

I was fooling with some data using cut, sed, etc.   When I needed to sum up all of the numbers, I used to do this with a Perl script (years ago), but it's a one liner in Ruby now:
cat numbers | ruby -e 'puts ARGF.collect {|l| l.match(/^ *(\d+)/)[1].to_i}.inject(0, &:+)'
This uses the Ruby 1.9 ARGF feature and matches just the first number listed (possibly preceded by spaces), converts them to an array of integers, then sums them using Array#inject.