Bash – Human-readable filesize with find’s printf

bashfindprintf

I am writing a simple helper function to show a specific folder in the format I want:

find . -maxdepth 1 -not -name "." -printf '[%TY-%Tm-%Td]\t%s\t%f\n' | sort -n

However I want to show the filesizes in a nicer format. I found this answer which I used to create a bash function called hr.

user@host:~$ hr 12345
12M

I tried using this in the find call as so:

find . -maxdepth 1 -not -name "." -printf '[%TY-%Tm-%Td]\t'$(hr %s)'\t%f\n' | sort -n

But it still continues to show the full filesize. How should I modify this so it works as expected?

Best Answer

Assuming sane file names, with numfmt from gnu coreutils (8.21 or later):

find . -type f -printf '[%TY-%Tm-%Td]\t%s\t%f\n' | numfmt --field=2 --to=iec-i

You can further format the output via --padding= and --format= options (and with most recent versions even set output precision) e.g:

... |  numfmt --field=2 --to=iec-i --suffix=B --padding=8

or

... |  numfmt --field=2 --to=iec-i  --format='%10.3f'

If you don't mind the permissions & links-count columns, with gnu ls:

ls -gohAt --time-style=+%Y-%m-%d
Related Question