23

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 -hoption (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 163564736into 156M and 13209 into 13K and also does the reverse?

Svaberg
  • 1,501
  • 1
  • 19
  • 40

2 Answers2

54

numfmt

To:

echo "163564736" | numfmt --to=iec

From:

echo "156M" | numfmt --from=iec
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • This seems to be exactly what I was looking for. For the reverse it is `echo "156M" | numfmt --from=iec`. Do want to add that to the answer? – Svaberg May 04 '16 at 04:25
  • Note, the pipe is not required, the `numfmt` also supports `numfmt --to=iec 163564736` and `numfmt --from=iec 156M`... – Stefan Mar 21 '23 at 08:50
2

There is no standard (cross-platform) tool to do it. But solution using awk is described here

Community
  • 1
  • 1
sqr163
  • 1,074
  • 13
  • 24
  • I guess [numfmt](https://www.gnu.org/software/coreutils/manual/html_node/numfmt-invocation.html), suggested in another answer, is cross-platform in the linux world? – Svaberg May 04 '16 at 04:39
  • @Svaberg Sure it is! If you follow POSIX and a bunch of other rules, your shell scripts can be the most portable software ever created: they will work properly on any Linux, FreeBSD, UNIX, MAC, Android... – sqr163 May 05 '16 at 22:54
  • I see. So when, in your answer, you say that "there is no standard (cross-platform) tool", do you mean that numfmt is not standard? – Svaberg May 06 '16 at 05:37
  • 1
    @Svaberg Yes, precisely. `numfmt` is part of GNU coreutils from 2013, but `awk` in contrast is essential part of classic UNIX shell since 1970s, standardized by POSIX since 1990s, and likely lives even inside your mobile phone... – sqr163 May 06 '16 at 08:00
  • ...if only I could use awk on my iPhone :D – Sridhar Sarnobat Jun 08 '23 at 21:08