Bash – How to Sort by Human Readable Sizes Numerically

bashsort

for example I have command that shows how much space folder takes

du folder | sort -n

it works great, however I would like to have human readable form

du -h folder

however if I do that than I cannot sort it as numeric.

How to join du folder and du -h folder to see output sorted as du folder, but with first column from du -h folder

P.S. this is just an example. this technique might be very useful for me (if its possible)

Best Answer

Here is a more general approach. Get the output of du folder and du -h folder in two different files.

du folder > file1
du -h folder > file2

The key part is this: concatenate file1 and file2 line by line, with a suitable delimiter.

paste -d '#' file1 file2 > file3

(assuming # does not appear in file1 and file2)

Now sort file3. Note that this will sort based on file1 contents and break ties by file2 contents. Extract the relevant result using cut:

sort -n -k1,7 file3 | cut -d '#' -f 2

Also take a look at man sort for other options.


You may also save this as an alias, for later re-use. To do so, add the following to the bottom of ~/.bashrc:

sorted-du () {
    paste -d '#' <( du "$1" ) <( du -h "$1" ) | sort -n -k1,7 | cut -d '#' -f 2
}

Then, open a new terminal session and execute your new alias:

sorted-du /home
Related Question