How to find the largest file in a directory and its subdirectories? How to find the largest file in a directory and its subdirectories? bash bash

How to find the largest file in a directory and its subdirectories?


Quote from this link-

If you want to find and print the top 10 largest files names (not directories) in a particular directory and its sub directories

$ find . -printf '%s %p\n'|sort -nr|head

To restrict the search to the present directory use "-maxdepth 1" with find.

$ find . -maxdepth 1 -printf '%s %p\n'|sort -nr|head

And to print the top 10 largest "files and directories":

$ du -a . | sort -nr | head

** Use "head -n X" instead of the only "head" above to print the top X largest files (in all the above examples)


To find the top 25 files in the current directory and its subdirectories:

find . -type f -exec ls -al {} \; | sort -nr -k5 | head -n 25

This will output the top 25 files by sorting based on the size of the files via the "sort -nr -k5" piped command.

Same but with human-readable file sizes:

find . -type f -exec ls -alh {} \; | sort -hr -k5 | head -n 25


find . -type f | xargs ls -lS | head -n 1

outputs

-rw-r--r--  1 nneonneo  staff  9274991 Apr 11 02:29 ./devel/misc/test.out

If you just want the filename:

find . -type f | xargs ls -1S | head -n 1

This avoids using awk and allows you to use whatever flags you want in ls.

Caveat. Because xargs tries to avoid building overlong command lines, this might fail if you run it on a directory with a lot of files because ls ends up executing more than once. It's not an insurmountable problem (you can collect the head -n 1 output from each ls invocation, and run ls -S again, looping until you have a single file), but it does mar this approach somewhat.