I have a web server where I have run out of space and it's causing issues with the WordPress sites I am running on them.

I know that I have a lot of large .png files (the fact that it's PNG is a mistake in itself, but let's not get into that).

I would like to get the list of PNG or JPEG files that are on the server and sort them by decreasing size. I know I can use ls -SlahR, but the sorting is on a per-folder basis.

I then came up with find . -name "*.png" | xargs -i -n1 ls -lah {} which is OK except that (a) it doesn't sort the lines and (b) it shows the file permissions and ownerships which I couldn't care less about.

So is there something better? Something that would produce [size] [path_to_file]?

  • 1
    Is this really UNIX or do you mean Linux? Do you have access to the GNU versions of the classic tools? – terdon Sep 27 '14 at 13:31

You could use a combination of find, du and sort like the following:

find <directory> -iname "*.png" -type f -print0 | xargs -0 -n1 du -b | sort -n -r

This searches for all regular files in <directory> ending with .png (case-insensitive). The result is then passed to xargs which calls du with each single file, getting its size in bytes (due to -b) and passed to sort, which sorts the result numerically (-n) by the file size in decreasing order (-r). The -print0 is used to separate the results by \0 instead of \n, so you can have paths with strange characters like spaces and newlines.


You can just do the whole thing with (GNU) find and sort, no need for du:

$ find . -iname '*png' -printf '%s %p\n' | sort -rn
68109 ./7.png
21751 ./2.png
21751 ./1.png
5393 ./6.png
2542 ./5.png
1717 ./4.png
1003 ./3.png
878 ./10.png
793 ./9.png
587 ./8.png
  • Not every find has -printf (e.g. NetBSD's find in the base system). find ...|stat ...|sort ... can help then... – yeti Sep 27 '14 at 13:47
  • 1
    @yeti I know, that's why I asked the OP to clarify if they have access to the GNU tools. – terdon Sep 27 '14 at 13:52

And just in case you need to have the most compatible version, you can do it with regular find and sort (no reliance on gnu extensions, such as printf):

find . -ls | grep -i -e '\.png$' -e '\.jpe*g' | sort -k7,7nr

-k7,7 : Sort on columns 7 to 7 (ie, only 7) (... this should be a parameter, allowing one to change the column number in case on their old system find -ls output sizes in bytes on a different column)

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.