Skip to content

Instantly share code, notes, and snippets.

@maboloshi
Last active June 19, 2023 18:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maboloshi/04f3e9845753b482abe825d3b1a8cc4e to your computer and use it in GitHub Desktop.
Save maboloshi/04f3e9845753b482abe825d3b1a8cc4e to your computer and use it in GitHub Desktop.
[To convert bytes to human readable value] To convert bytes to KB, MB, GB... for human readable. #shell

To convert bytes to KB, MB, GB... for human readable

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

@Geczy
Copy link

Geczy commented Jun 19, 2023

tysm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment