Member Avatar for Member #701526
Member #701526

Dear Folks,

Using bash on Linux, how would I list file sizes to 3 significant figures in human-friendly form?

If I try

ls -lh

I get 2 significant figures, but I would like to get 3 significant figures.

Also, there is the almighty muddle between megabytes and mebibytes that leads to confusion about what is being really output, but I am happy with either version so long as I get three sig figs and know whether it is mega or mebi :-)

TIA.

Dani AI

Generated

wanted three significant figures in a human-readable file-size listing (and an explicit choice of SI vs IEC units). A reliable pattern is to print exact byte counts and then reformat them with a small formatter that uses a printf-style %g conversion (which gives significant‑digit control) and appends clear unit labels (kB/MB for 1000, KiB/MiB for 1024).

Example (IEC / 1024 units, safe for filenames with spaces — uses GNU find + Perl):

find . -maxdepth 1 -type f -printf '%s\t%p\0' | perl -0 -ne '
  chomp;
  ($s,$name) = split(/\t/, $_, 2);
  @u = ("B","KiB","MiB","GiB","TiB","Pi");
  $i = 0;
  while ($s >= 1024 && $i < @u-1) { $s /= 1024; $i++ }
  printf("%.3g%s\t%s\n", $s, $u[$i], $name);
'

Notes and quick variants:

  • To use SI (1000) units, change 1024 to 1000 and use unit names like kB,MB,GB in @u.
  • A simpler GNU-only variant can use stat -c '%s\t%n' * | ... as the input if filenames with embedded newlines are not a concern. On BSD/macOS the stat syntax differs (for example stat -f '%z\t%N').
  • printf("%.3g", value) yields three significant figures; both awk and Perl support %g/%G formatting if a pure‑awk variant is preferred. See the awk/Perl docs for sprintf behavior. (gnu.org)

Why not just use GNU numfmt for the final display? numfmt can convert fields to SI/IEC units, but its --format accepts only a %f directive (fixed decimals), not %g (significant‑digit format), so it cannot directly emit “three significant figures” across arbitrary magnitudes; it is still handy for fixed‑decimal formatting or for converting raw bytes to labeled SI/IEC units. (gnu.org)

Troubleshooting: watch for filenames containing tabs or NULs (use -print0/-0 as shown), confirm which stat is present on the platform, and choose 1000 vs 1024 explicitly so the output label matches the scale.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.