ファイルリストからファイルサイズの合計を出力するスクリプト

パスが通っているところにfilesize.plで保存して実行権限つけたとして
こんな感じで使える

$ find -type f | filesize.pl -h
2.27K

#!/usr/bin/perl

use strict;
use Getopt::Std;

# commandline options
my %opts;
getopt('kmgt', \%opts);


# Read filelist and count file size
my $size = 0;
while(<>){
    chomp;
    $size += (-s $_);
}

# Format
if (exists($opts{'h'})){
    if ($size > 1024 * 1024 * 1024 * 1024){
        $opts{'t'} = 1;
    }
    elsif ($size > 1024 * 1024 * 1024){
        $opts{'g'} = 1;
    }
    elsif ($size > 1024 * 1024){
        $opts{'m'} = 1;
    }
    elsif ($size > 1024){
        $opts{'k'} = 1;
    }
}

if (exists($opts{'k'})){
    $size = sprintf("%.2fK", $size / 1024);
}
elsif (exists($opts{'m'})){
    $size = sprintf("%.2fM", $size / 1024 / 1024);
}
elsif (exists($opts{'g'})){
    $size = sprintf("%.2fG", $size / 1024 / 1024 / 1024);
}
elsif (exists($opts{'t'})){
    $size = sprintf("%.2fT", $size / 1024 / 1024 / 1024 / 1024);
}


# Output
print "$size\n";