Finding files on a Unix server and sorting by size

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]?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

$ find . -iname '*png' -printf '%s %pn' | 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

Method 2

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 instead of n, so you can have paths with strange characters like spaces and newlines.

Method 3

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)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x