Skip to content

Instantly share code, notes, and snippets.

@loretoparisi
Last active September 12, 2020 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loretoparisi/c43c605871689822e1d06892af2e4a39 to your computer and use it in GitHub Desktop.
Save loretoparisi/c43c605871689822e1d06892af2e4a39 to your computer and use it in GitHub Desktop.
how to sum file size from ls like output log with Bytes, KiB, MiB, GiB - https://stackoverflow.com/questions/63858674/how-to-sum-file-size-from-ls-like-output-log-with-bytes-kib-mib-gib
#!/bin/bash
count() {
awk 'BEGIN {
unit["Bytes"] = 1;
unit["kB"] = 10**3;
unit["MB"] = 10**6;
unit["GB"] = 10**9;
unit["TB"] = 10**12;
unit["PB"] = 10**15;
unit["EB"] = 10**18;
unit["ZB"] = 10**21;
unit["YB"] = 10**24;
unit["KB"] = 1024;
unit["KiB"] = 1024**1;
unit["MiB"] = 1024**2;
unit["GiB"] = 1024**3;
unit["TiB"] = 1024**4;
unit["PiB"] = 1024**5;
unit["EiB"] = 1024**6;
unit["ZiB"] = 1024**7;
unit["YiB"] = 1024**8;
}
{
if($4 in unit) total += $3 * unit[$4];
else printf("ERROR: Cant decode unit at line %d: %s\n",NR, $0);
}
END {
binaryunits[0] = "Bytes";
binaryunits[1] = "KiB";
binaryunits[2] = "MiB";
binaryunits[3] = "GiB";
binaryunits[4] = "TiB";
binaryunits[5] = "PiB";
binaryunits[6] = "EiB";
binaryunits[7] = "ZiB";
binaryunits[8] = "YiB";
for(i=8; i>=0; --i) {
if(total >= (1024**i)) {
printf("%f %s %f\n", total/(1024**i), binaryunits[i], total);
break;
}
}
}'
}
count $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment