brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: numfmt --to=iec turns byte counts into readable sizes like 1.5G

Linux
~/tips/tip-shell-numfmt-to-iec-human-readable

echo 1610612736 | numfmt --to=iec

Converts plain numbers into human-readable sizes, and works on any number that you pipe into it.

Plenty of commands print raw byte counts, and nobody enjoys counting digits. ls -h and du -h can do it for themselves, but numfmt does it for any number.

echo 1610612736 | numfmt --to=iec
numfmt --to=iec-i 1610612736

The first command prints 1.5G. The iec unit scales by 1024 and uses single-letter suffixes such as K, M and G. The second command uses iec-i and prints 1.5Gi, which is the form with the two-letter symbols that the GNU manual says the standard recommends.

It becomes useful in a pipeline. Say a script prints sizes in bytes in the first column of a file. You can convert that column in place:

cat sizes.txt | numfmt --to=iec --field=1

There is also the opposite direction, --from=iec, which reads values like 1.5G back into plain numbers. That is handy before you sort, because sort -h is not always an option inside a larger script.

The caveat is the base. The iec unit means powers of 1024, but disk vendors and many tools use 1000. If you compare with a number from a disk label, use --to=si instead, or a 1 TB drive will look smaller than it is. Also, numfmt is part of GNU coreutils, so a stock macOS shell may not have it unless you install coreutils.

Further reading: GNU coreutils: numfmt, numfmt(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link