: ########################################################################## # Title : bytes - print bytes used for specified files # Author : Heiner Steven # Date : 1995-01-01 # Requires : nawk # Category : File Utilities # SCCS-Id. : @(#) bytes 1.5 05/04/29 ########################################################################## # Description # Calculates sizes of multiple files, and prints them in a # human readable format, automatically chosing the right # orders of magnitude. # # Tries to work with SysV and BSD "ls", but may fail in certain # cases. Set the variable LS and/or SizeCol below if you # encounter problems on your system. # # Bugs # o should dive into e.g. "/bin" instead of printing "0 bytes" ########################################################################## PN=`basename "$0"` # Program name VER='1.5' : ${NAWK:=nawk} # The following variables may be set to an "ls" program and the # column the file size is printed in (first column has number 1). LS="ls" # print names of files LSL="$LS -l" # long list, look into directories LSD="$LSL -d" # long list, no subdirectories SizeCol= # usually 4 (BSD) or 5 (SysV) usage () { echo >&2 "$PN - byte totals for specified files, $VER usage: $PN [-hl] [file ...] -l: print file names -h: print this usage summary" exit 1 } Totals=true while [ $# -gt 0 ] do case "$1" in -l) Totals=false;; --) shift; break;; -h) usage;; -*) usage;; *) break;; # First file name esac shift done # Find out if the size is printed in the 4th (BSD) or the 5th (SysV) column. # Note that this heuristic will fail if on SysV a group id is printed # numerically l(e.g. because the name is not in /etc/group). In that case the # SizeCol variable above should be set manually. : ${SizeCol:=`$LSD . | awk ' NF >= 4 && $4 ~ /[^0-9]/ { print 5; exit (0); } { print 4; exit (0); } '`} : ${NameCol:='NF'} # "NF" is the last column number in AWK if [ $# -gt 0 ] then : ${Totals:=false} $LSL "$@" else : ${Totals:=true} #set -- `$LS -d * .[!.]* ..?* 2>/dev/null` $LSL "$@" fi | $NAWK ' function fmtnumber(s, line, i, rounded) { line = sprintf ("%.0f bytes", s) for ( i=1; i<=n; ++i ) { rounded = int ( (s + 512) / 1024) s = int (s / 1024) if ( s > 0 ) line = line sprintf (", %.0f %s", rounded+0, om [i]) } return line } BEGIN { # Orders of magnitude: # kilo 10^3 mega 10^6 giga 10^9 # tera 10^12 peta 10^15 exa 10^18 n = split ("KB MB GB TB PB EB", om) totals = ("'"$Totals"'" == "true" ) } $1 ~ /^-/ { fsize = $'"$SizeCol"' if ( !totals ) { name = $'"$NameCol"' print name "\t" fmtnumber(fsize) } s += fsize ++nfiles }; END { line = "file(s)=" nfiles+0 if ( totals ) line = line ", total" line = line sprintf ("\t%.0f bytes", s) for ( i=1; i<=n; ++i ) { rounded = int ( (s + 512) / 1024) s = int (s / 1024) if ( s > 0 ) line = line sprintf (", %.0f %s", rounded+0, om [i]) } print line }'