How to list files in a directory, sorted by size, but without listing folder sizes?

Issue

I’m writing a bash script that should output the first 10 heaviest files in a directory and all subfolders (the directory is passed to the script as an argument).
And for this I use the following command:
sudo du -haS ../../src/ | sort -hr
, but its output contains folder sizes, and I only need files. Help!

Solution

Would you please try the following:

dir="../../src/"
sudo find "$dir" -type f -printf "%s\t%p\n" | sort -nr | head -n 10 | cut -f2-
  • find "$dir" -type f searches $dir for files recursively.
  • The -printf "%s\t%p\n" option tells find to print the filesize
    and the filename delimited by a tab character.
  • The final cut -f2- in the pipeline prints the 2nd and the following
    columns, dropping the filesize column only.

It will work with the filenames which contain special characters such as a whitespace except for
a newline character.

Answered By – tshiono

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published