3

Using ls -lSrh I get this output:

-rw-rw-r-- 1 a a 2.4K Feb 15 04:44 10010.png
-rw-rw-r-- 1 a a 2.4K Feb 15 04:43 1000.png
-rw-rw-r-- 1 a a 2.4K Feb 15 04:44 10009.png
-rw-rw-r-- 1 a a 2.4K Feb 15 04:44 10008.png
-rw-rw-r-- 1 a a 2.4K Feb 15 04:43 10004.png
-rw-rw-r-- 1 a a 2.4K Feb 15 04:43 10000.png

How can I delete all .png files with the specific 2.4K size?

1
  • 1
    Try find with condition -size. Print the file names first in order to check the result. If it matches your expectations, you can add the -delete action.
    – Bodo
    Commented Feb 16, 2023 at 16:26

1 Answer 1

4

Bodo's comment points you at the right direction, but things are a bit trickier than they seem. That is because the file size you see in the ls -lSrh output is not the exact size of the files, but the file size in human readable format, due to the use of the -h flag. To use find to find the files of a specific file size, however, you need to know the exact size of the files, so you need to run the command:

ls -lSr

that is the ls command you used, but without the -h flag, which outputs file sizes in bytes.

If you run this command, then you will most likely find that all these files that previously seemed to all have the exact same size of 2.4K have somewhat different sizes now. What you need to do is determine the lower and the upper file size limits of the files you want to delete and then run the following find command from within the directory your files are located in:

find . -type f -name "*.png" -size +<lower_limit>c -size -<upper_limit>c -delete

Explanation of the above command:

  • .: search in the current directory.

  • -type f: search for files only, not directories.

  • -name "*.png": search for files that their name ends with .png.

  • -size +<lower_limit>c -size -<upper_limit>c: search for files with sizes between the <lower_limit> and <upper_limit>, in other words for files larger than the <lower_limit> (that's what + means) and lower than the <upper_limit> (that's what - means). The c suffix that follows <lower_limit> and <upper_limit> is used to tell find that the sizes are in bytes, which is what you get for the file sizes from ls -lSr.

  • -delete: delete the found files that fulfill the above criteria.


CAUTION:

First run the above command without -delete to make sure that it lists the correct files! If you are satisfied with the output, then and only then add -delete!

The -delete action deletes the found files permanently, so you will not be able to recover them in case of a mistake. Always make sure to keep a backup of the original files in case something goes wrong.


References:

1
  • 1
    It might be more useful to use find's own action -ls instead of -delete for a dry-run as it will show file sizes in an ls style output while the default find's -print action won't.
    – Raffa
    Commented Nov 27, 2023 at 8:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .