Groovy web console

subscribe to the feed Subscribe
to this
site

Human readable file size to bytes

Published 2 months ago by Lucas Moten with tags file convert string
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
// Convert a human readable file size into a number of bytes
// This is intended to model the split command usage of the same
def s = '4G'
def lengthFromHumanSize(s) 
{
  try { return Long.valueOf(s) }
  catch(NumberFormatException nfe) {
    r = (s =~ /(\d+)/).findAll()
    if(r.size() > 0)
    {
      f = Long.valueOf(r[0][0])
      if(s.indexOf('KB') > -1) return f * Math.pow(1000,1).longValue()
      if(s.indexOf('MB') > -1) return f * Math.pow(1000,2).longValue()
      if(s.indexOf('GB') > -1) return f * Math.pow(1000,3).longValue()
      if(s.indexOf('TB') > -1) return f * Math.pow(1000,4).longValue()
      if(s.indexOf('PB') > -1) return f * Math.pow(1000,5).longValue()
      if(s.indexOf('EB') > -1) return f * Math.pow(1000,6).longValue()
      if(s.indexOf('K') > -1) return f << 10
      if(s.indexOf('M') > -1) return f << 20
      if(s.indexOf('G') > -1) return f << 30
      if(s.indexOf('T') > -1) return f << 40
      if(s.indexOf('P') > -1) return f << 50
      if(s.indexOf('E') > -1) return f << 60
    }
    return -1
  }
}
println(s)
println(lengthFromHumanSize(s))