How do I recursively remove files that are less than 1MB in size from a directory?

link|improve this question
feedback

migrated from stackoverflow.com Feb 9 at 7:15

This question came from our site for professional and enthusiast programmers.

5 Answers

This can be done with find:

find -type f -size -1M -exec rm {} +

Note that this will recursively descend into subdirectories, and will unconditionally delete all files smaller than 1 megabyte. Be careful.

link|improve this answer
you're missing the path argument to find – Useless Feb 8 at 12:25
@Useless: That's GNU find. :) – Sven Marnach Feb 8 at 12:29
I never knew it let you omit that! – Useless Feb 8 at 12:31
@Useless: It does, but other versions of find don't, so if you want portability, you should include a directory argument. – Sven Marnach Feb 8 at 12:35
1  
@DanielAndersson: find restricts the number of arguments to the called process to fit into the system's limits, in contrast to rm *, which is guranteed to be a single process invocation. find will invoke multiple instance of rm if necessary. And I'm pretty sure that special characters are treated correctly, including newline characters. I prefer -exec rm over -delete for flexibility reasons -- as an example, the latter offers no way to delete write-protected files. – Sven Marnach Feb 13 at 11:57
show 2 more comments
feedback

This should do the job:

$ find <directory> -type f -size -1M -delete
link|improve this answer
feedback

Just for variety and a possible (probably marginal) performance gain:

find <directory> -type f -size -1M -print0  | xargs -0 rm
link|improve this answer
How is this supposed to be faster? It starts an additional xargs process. – Sven Marnach Feb 8 at 12:33
Now you can have two CPUs contending for the same block device! More sensibly, the stat/readdir operations aren't synchronously blocked by the unlink operation. Whether this is likely to be better obviously depends on the subtree size, number of files, device etc. – Useless Feb 8 at 12:36
feedback

Try

find . -size -1M -exec rm {} \;

link|improve this answer
feedback

You can checkout this link http://ayaz.wordpress.com/2008/02/05/bash-quickly-deleting-empty-files-in-a-directory/ , it has exactly what you want.

link|improve this answer
Answers on SO should be self-contained -- don't post a mere link. (Moreover, the code in the linked post deletes empty files rather than files smaller than 1M.) – Sven Marnach Feb 8 at 12:32
@SvenMarnach can't we use $file_size < 1M in the given code example link. – Ravia Feb 8 at 12:36
No, we can't, since the shell won't understand 1M. – Sven Marnach Feb 8 at 12:43
By 1M I meant 1048576 converting 1MB to byte – Ravia Feb 8 at 13:01
1  
Well, if you test if this really works and copy the code to your answer, this might become an SO answer. – Sven Marnach Feb 8 at 13:06
feedback

Your Answer

 
or
required, but never shown