mike@shiner $ cat file-with-numbers
1
2
3
4
5
6
We can sum up the values in this file with the following command.
mike@shiner $ cat file-with-numbers | awk '{sum+=$1}END{print sum}'
21
We can see here that the sum of the numbers in the file total to 21.
# In ruby:
ReplyDeletesum = 0
File.open('numbers').each { |line| sum += line.to_i }
puts sum
Any more difficult than your example and I'd certainly fall back on a scripting language.
I agree. Is there a way to run that from the command line? Your example made me think of the following perl one-liner:
ReplyDeletecat file-with-numbers | perl -ne '$n += $_; print $n if eof'
ruby -e "sum=0;File.open('numbers').each { |line| sum += line.to_i };puts sum"
ReplyDeleteRun from the same directory the file is in.
Or, chaining together a bunch of method calls to do this in one statement:
ReplyDeleteruby -e "puts File.open('numbers').read.split.inject(0) {|result, element| result + element.to_i}"
But this starts to get a bit crazy. But is it worse than your whacky perl '$' variables?
After some playing i think i got a more cryptic ruby version...
ReplyDeleteruby -e "puts eval File.open('numbers').read.split.join('+')"
Otto,
ReplyDeleteHah..nice. I had no idea you could call eval on a string like that and have it work. That language surprises me daily still.
I really like the pure awk solution. Simple. Tweakable (for files that have the num in a different column) and succinct. Nice work. Don't need the cat though ;)
ReplyDeleteawk '{n+=$1}END{print n}' file-with-numbers
I can't let otto always one up me with ruby so here the ganky php solution.
ReplyDeletecat numfile | php -R '@$c+=$argn;' -E 'print($c);'
This one is pretty pure. No programming languages involved.
ReplyDeleteecho `cat file-with-numbers` | tr ' ' '+' | bc