Example:
file_size=123456778
echo $file_size | awk '{ split( "B KB MB GB TB PB EB ZB YB" , v ); s=1; while( $1>1024 && s<9 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }'
或者
echo $file_size | awk '{ split( "B KB MB GB TB PB EB ZB YB" , v ); for( s=1; $1>1024 && s<9; s++ ) $1/=1024; printf "%.2f %s", $1, v[s] }'
Example output:
117.74 MB
Breaking it down for readability:
BEGIN {
# Only need do this once, allow for bigger files.
split("B KB MB GB TB PB EB ZB YB", v)
}
{
# Select B suffix.
s=1
# Need higher suffix, but stop at YB.
while ($5 > 1024 && s < 9)
{
# Divide by 1K, go to next suffix.
$5 /= 1024
s++
}
# Pretty-print the line.
printf "%6.2f %-2s %s\n", $5, v[s], $9
}
Edited from:
https://stackoverflow.com/a/47709545/7488424
tysm