Svaberg Svaberg - 7 months ago 35
Bash Question

Convert between byte count and "human-readable" string

Is there a shell command that simply converts back and forth between a number string in bytes and the "human-readable" number string offered by some commands via the

-h
option?

To clarify the question:
ls -l
without the
-h
option (some output supressed)

> ls -l
163564736 file1.bin
13209 file2.bin


gives the size in bytes, while with the
-h
option (some output supressed)

> ls -lh
156M file1.bin
13K file2.bin


the size is human readable in kilobytes and megabytes.

Is there a shell command that simply turns
163564736
into
156M
and
13209
into
13K
and also does the reverse?

Answer

numfmt

To:

echo "163564736" | numfmt --to=iec

From:

echo "156M" | numfmt --from=iec