There are a couple of perl
modules on CPAN: Format::Human::Bytes and Number::Bytes::Human, the latter one being a bit more complete:
$ echo 100 1000 100000 100000000 |
perl -M'Number::Bytes::Human format_bytes' -pe 's/\d{3,}/format_bytes($&)/ge'
100 1000 98K 96M
$ echo 100 1000 100000 100000000 |
perl -M'Number::Bytes::Human format_bytes' -pe 's/\d{3,}/
format_bytes($&,bs=>1000, round_style => 'round', precision => 2)/ge'
100 1.00k 100k 100M
And the reverse:
$ echo 100 1.00k 100K 100M 1Z |
perl -M'Number::Bytes::Human parse_bytes' -pe '
s/[\d.]+[kKMGTPEZY]/parse_bytes($&)/ge'
100 1024 102400 104857600 1.18059162071741e+21
NOTE: the function parse_bytes()
was added in version 0.09 (2013-03-01)