How do I delete all files smaller than a certain size in all subfolders?

88

27

I have a folder with many sub-folders containing small tif files (less than 160kb) which have been merged together in bigger pdf files, together with some big multi-page tif files.

I want to delete all small tif files without deleting the bigger files (tif or pdf) and retaining the directory structure. How do I go about it on Linux using the command-line?

To Do

Posted 2013-09-12T09:57:40.587

Reputation: 1 772

Answers

158

find . -name "*.tif" -type 'f' -size -160k -delete

Run the command without -delete first to verify that the correct files are found.

Note the - before 160k. Just 160k means exactly 160 kilobytes. -160k means smaller than 160 kilobytes. +160k means larger than 160 kilobytes.

The -type 'f' forces the command to only act on files and skip directories. this would avoid errors if the path contains folders with names that match the pattern *.tif.

If you want to filter size in bytes (as in 160 bytes instead of 160 kilobytes) then you have to write it like this: 160c. If you just write 160 it will be interpreted as 160*512 bytes. This is a strange requirement by POSIX. Read here for more details: https://unix.stackexchange.com/questions/259208/purpose-of-find-commands-default-size-unit-512-bytes

lesmana

Posted 2013-09-12T09:57:40.587

Reputation: 14 930

The ubuntu man page seems to mention this. Just below the "TESTS" section:

Numeric arguments can be specified as +n for greater than n, -n for less than n, n for exactly n. – jdg – 2014-09-11T23:55:49.700

1thanks. it did not occur to me that the information might be somewhere else in the manpage. – lesmana – 2014-09-12T08:55:44.693

It is nice this command also works recursively. My use case would be to delete .txt files under 12kB. – Sun – 2014-09-23T04:21:58.183

no need for sudo? – Jean-François Gagnon – 2015-10-06T15:35:35.947

On OSX I needed to add the current folder (dot): find . -name "*.JPG" -size -100k -delete – TCB13 – 2015-10-30T13:17:09.617

11For sizes in bytes specify 50c, not 50b or 50! – Evengard – 2016-01-29T13:43:31.773

and what about if I want to exclude subfolders? – hipoglucido – 2017-11-17T09:46:47.520

very useful, been looking for a one liner :) – Maciej Cygan – 2018-02-14T15:55:23.690

Weirdly, -2k isn't inclusive of files that are exactly 2 kilobytes - it only matches files that are less than 2 kilobytes. This means you would have to additionally run -size 2k to get those files that are exactly 2 kilobytes. – Hashim – 2020-01-10T22:26:21.603