I'm writing a bash script that should output the first 10 heaviest files in a directory (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!
CodePudding user response:
Why using du
at all? You could do a
ls -S1AF
This will list all entries in the current directoriy, sorted descending by size. It will also include the names of the subdirectories, but they will be at the end (because the size of a directory entry is always zero), and you can recognize them because they have a slash at the end.
To exclude those directories and pick the first 10 lines, you can do a
ls -S1AF | head -n 10 | grep -v '/$'
CodePudding user response:
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 tellsfind
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.