How to Sort Human Readable Size

findlssort

I'm basically looking for files then sorting by the size. The script works if I don't sort the size by human readable. But I want the size to be human readable. How can I sort sizes that are human readable?

For example:

 ls -l | sort -k 5 -n | awk '{print $9 " " $5}'

This works as expected, I got the size of my files in bytes ascending:

1.txt 1
test.txt 3
bash.sh* 573
DocGeneration.txt 1131
andres_stuff.txt 1465
Branches.xlsx 15087
foo 23735
bar 60566
2016_stuff.pdf 996850

Now, I want the size to be human readable, so I added an -h parameter to ls, and now some files are out of order:

 ls -lh | sort -k 5 -n | awk '{print $9 " " $5}'
1.txt 1
DocGeneration.txt 1.2K
andres_stuff.txt 1.5K
test.txt 3
Branches.xlsx 15K
foo 24K
bar 60K
bash.sh* 573
2016_stuff.pdf 974K

Best Answer

Try sort -h k2

-h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)

It is part of gnu sort, BSD sort, and others.