开发者

Calculate sum of size notated figures?

I want to calculate the total size of all .mobi files from this link (it's a good link by the way).

In my attempt of making this as my learning experien开发者_StackOverflow社区ce, I have made a 'pipe' (let's call it a) that output all the sizes from that page which looks like:

189K
20M
549K
2.2M
1.9M
3.1M
2.5M
513K
260K
1.1M
2.8M
5.1M
3.7M
1.5M
5.6M
1.0M
5.6M
1.5M
4.9M
3.4M
810K

My target is to get the total size (ex: 50.50M, or 50000K) - sum of all these numbers. My question is, how to calculate that target, using pipeling (a | some_other_commands). Answers using python or any other language (preferably one liners) are welcome. Thanks a lot.


For the fun a solution in shell:

a | sed -e 's/M$/ 1024 * +/'  -e 's/K$/ +/'  | dc -e '0' -f - -e 'p'


Perl one-liner:

a | perl -ne 's/^([\d.]+)M$/$1*1024/e;$sum+=$_; END{print $sum."K"}'

see it

It assumes that all entries are in either Kilobytes or Megabytes as shown in OPs input.


Sigh, someone says “one-liner” and all my code-golf reflexes fire...

ruby -e 'puts $<.read.split.inject(0){ |m,e| m += e.to_f * { "M" => 1, "K" => 0.001 }[e[-1,1]]}.to_s+"M"'

or, with some shortcuts...

ruby -ne 'p @e=@e.to_f+$_.to_f*{"M"=>1,"K"=>0.001}[$_[-2,1]]'

Update: Heh, ok, hard to read. The OP asked for a "one liner". :-)

#!/usr/bin/env ruby
total = 0
while s = gets                                       # get line
  scalefactorMK = s.chomp[-1,1]                      # get the M or K
  scalefactor = { 'M'=>1,'K'=>0.001 }[scalefactorMK] # get numeric scale
  total += s.to_f * scalefactor                      # accumulate total
end
puts "%5.1fM" % [total]


if you have Ruby (1.9+)

require 'net/http'
url="http://hewgill.com/~greg/stackoverflow/ebooks/"
response = Net::HTTP.get_response( URI.parse(url) )
data=response.body
total=0
data.split("\n").each do |x|
    if x=~/\.mobi/
        size = x.split(/\s+/)[-1]
        c = case size[-1]
            when 'K' then 1024
            when 'M' then 1024 * 1024
            when 'G' then 1024 * 1024 * 1024
        end
        total+=size[0..-1].to_i * c
    end
end
puts "Total size: %.2f MB" %  ( total/(1024.0 * 1024.0) )


awk (assume files less than 1K don't substantially add to the total):

a | awk '/K/ {sum += $1/1024} /M/ {sum += $1} END {printf("%.2fM\n", sum)}'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜