Search code examples
bashmacosterminalbatch-rename

Massively delete files with common prefix in terminal Mac OS X


I have a bunch of images like this:

enter image description here

I want to erase them all except those without the suffixes (-150x150, -256x256, etc).

For example, looking at the image above I want to keep only bg_section_2.jpg, bg_section_bw.jpg and bg_section_half_2.jpg and delete the others with prefixes.

The numbers of the sizes (-150x150...etc) are not the same in all the examples. But they have the same structure.

Many thanks for your time! :)


Solution

  • You can do this with find. The -regex option takes everything that has one or more numbers [0-9]+, followed by an x, in turn again followed by one or more numbers [0-9]+. Just make sure you test this first by copying the directory and check the results ;-)

    $ mkdir tmp
    $ cd tmp
    $ touch {a,b,c}.png; touch {a,b,c}-{10,11}x{150,4000}.png
    $ find . -type f -regex '.*[0-9]+x[0-9]+.*' -exec rm {} \;
    $ ls
    a.png  b.png  c.png
    

    As notified by s3cur3 (thanks!), you should add the -E flag on Mac:

    $ find -E . -type f -regex '.*[0-9]+x[0-9]+.*' -exec rm {} \;