Theres 99 folders with different size. I would like to know which one of these folders is the median depending on their size, and how to print the name of the folder when finding it ?
- The title says you want the median-sized file, and the body suggests you want the median-sized directory. I'll assume you mean directory.
- The directories are exactly one level deep - that is, you have directories
cetc., but not
- If multiple directories have the same size, you are happy with the result being any one of them.
- There are exactly 99 directories.
If any of these assumption is incorrect, please say and I'll try to update the answer.
du will tell you the size of everything in each directory, printing for each directory the size and the name. This will give you 100 lines: your 99 directories and one for the parent directory.
sort -g can sort the results in order of the numeric first field, which is the size. The median of 99 results will now be at the 50th line.
tail can select the 50th line.
So combine these:
cd ~/wherever/ du | sort -g | tail -n +50
First get a list of whatever you are counting and count the lines. The following works for both directories and files (replace $* with whatever you want to count):
du -s $* | wc -l
You said that this in your case is 99. Divide by 2 and add 1 to get the order number of the median file/folder. In your case this is 50.
Now extract the line containing the median size file/folder:
du -s $* | sort -n | tail -n +50 | head -1
(note that "du -s" does not include a file or directory added twice, for example "du -s /etc /etc/passwd" returns only a summary for /etc)