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 ?

  • You'll want to use the stat, sort, wc and head commands. Check their man pages – glenn jackman Oct 18 '18 at 19:50


  • 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 a, b, c etc., but not a/x.
  • 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.

The command 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.

The command 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.

The command tail can select the 50th line.

So combine these:

cd ~/wherever/
du | sort -g | tail -n +50
  • thank you so much for your answer. Im sorry for my english, its my 3rd language so its kinda hard explaining what I really need. Theres 99 files with different sizes. I need to know which one is at the median depending of its size of course. I think your answer is the right one, once I get home from work i will try it and let you know how it worked out! – SandraGevio Oct 18 '18 at 19:54

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.