Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  13] [ 0]  / answers: 1 / hits: 18525  / 1 Year ago, sun, december 18, 2022, 5:02:22

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)


More From » bash

 Answers
6

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

[#41995] Monday, December 19, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cheeturage

Total Points: 432
Total Questions: 111
Total Answers: 115

Location: Bahrain
Member since Tue, Mar 1, 2022
2 Years ago
;